use*_*246 13 .net c# truncate file
我正在使用Trace.Writeln()函数将C#中的程序执行的操作写入文件.但是文件变得太大了.如何在文件增长到1MB时截断它?
TextWriterTraceListener traceListener = new TextWriterTraceListener(File.AppendText("audit.txt"));
Trace.Listeners.Add(traceListener);
Trace.AutoFlush = true;
Run Code Online (Sandbox Code Playgroud)
应该添加到上面的块中
sll*_*sll 35
FileStream fileStream = new FileStream(...);
fileStream.SetLength(sizeInBytesNotChars);
Run Code Online (Sandbox Code Playgroud)
与自己尝试这样做相反,我真的建议使用像log4net这样的东西; 它内置了很多这种有用的功能.
小智 5
当文件超过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)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21808 次 |
最近记录: |