Ответ 1
Попробуйте поиграть с FileStream.SetLength
FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
Я пишу действия, выполняемые программой в С#, в файл с помощью функции Trace.Writeln(). Но файл становится слишком большим. Как обрезать этот файл, когда он вырастет до 1 МБ?
TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;
Что нужно добавить к вышеуказанному блоку
Попробуйте поиграть с FileStream.SetLength
FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
Закройте файл, а затем снова откройте его, используя FileMode.Truncate.
Некоторые реализации журналов архивируют старый файл под старым именем перед его повторным открытием, чтобы сохранить больший набор данных без слишком большого количества файлов.
В отличие от попыток сделать это самостоятельно, я бы рекомендовал использовать что-то вроде log4net; он имеет много таких полезных функциональных возможностей.
Когда файл превышает 500000 байт, он вырезает начало 250000 байт из файла, чтобы оставшийся файл имел длину 250000 байт.
FileStream fs = new FileStream(strFileName, FileMode.OpenOrCreate);
if (fs.Length > 500000)
{
// Set the length to 250Kb
Byte[] bytes = new byte[fs.Length];
fs.Read(bytes, 0, (int)fs.Length);
fs.Close();
FileStream fs2 = new FileStream(strFileName, FileMode.Create);
fs2.Write(bytes, (int)bytes.Length - 250000, 250000);
fs2.Flush();
} // end if (fs.Length > 500000)
Сделав это:
if(new FileInfo("<your file path>").Length > 1000000)
{
File.WriteAllText("<your file path>", "");
}
Возможно, это было бы простое решение:
// Test the file is more or equal to a 1MB ((1 * 1024) * 1024)
// There are 1024B in 1KB, 1024KB in 1MB
if (new FileInfo(file).length >= ((1 * 1024) * 1024))
{
// This will open your file. Once opened, it will write all data to 0
using (FileStream fileStream = new FileStream(file, FileMode.Truncate, FileAccess.Write))
{
// Write to your file.
}
}
Если у вас нет желания хранить содержимое или переместить их в вспомогательный файл, который отслеживает обновление для цикла (будь то днем или какой-либо другой длиной цикла), я бы рекомендовал просто переписать файл с помощью этого простого метода:
private void Truncate(readFile) // to clear contents of file and note last time it was cleared
{
string readFile = readPath + ".txt";
string str = string.Format("{0} : Truncated Contents", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
using (StreamWriter truncate = new StreamWriter(readFile))
{
truncate.WriteLine(str); // truncates and leaves the message with DateTime stamp
}
}
Если, с другой стороны, вы хотите сохранить содержимое в файл для даты, когда они были усечены, вы можете использовать следующий метод в сочетании с вышесказанным:
private void Truncate(readPath) // to clear contents of file, copy, and note last time it was cleared and copied
{
if (!File.Exists(readPath)) // create the new file for storing old entries
{
string readFile = readPath + ".txt";
string writeFile = readPath + DateTime.Now.ToString("_dd-MM-yyyy_hh-mm") + ".txt"; // you can add all the way down to milliseconds if your system runs fast enough
using (FileStream fs = new FileStream(writeFile, FileMode.OpenOrCreate, FileAccess.Write))
{
using (StreamWriter write = new StreamWriter(fs))
using (StreamReader file = new StreamReader(readFile))
{
write.WriteLine(string.Format(textA, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
string line;
var sb = new StringBuilder();
while ((line = file.ReadLine()) != null)
{
line = line.Replace("\0", ""); // removes nonsense bits from stream
sb.AppendLine(line);
}
write.WriteLine(sb.ToString());
string textB = "{0} : Copied Source";
write.WriteLine(string.Format(textB, DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")));
}
}
string str = string.Format("{0} : Truncated Contents", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt"));
using (StreamWriter truncate = new StreamWriter(readFile))
{
truncate.WriteLine(str); // truncates and leaves the message with DateTime stamp
}
}
}
В любом случае вы можете использовать метод по вашему выбору со следующим блоком:
if(new FileInfo("audit.txt").Length >= 0xfffff) // hex for 1MB
{
Truncate("audit");
}
Надеюсь, это поможет будущим читателям.
Спасибо,
C§