【发布时间】:2015-09-13 10:30:32
【问题描述】:
如果文本日志文件的大小超过最大值,我想清理一些卷:
FileInfo f = new FileInfo(filename);
if (f.Length > 30*1024*1024)
{
var lines = File.ReadLines(filename).Skip(10000);
File.WriteAllLines(filename, lines);
}
但我有例外
System.IO.IOException: The process cannot access the file '<path>' because it is being used by another process.
问题:
- 在以后使用文件之前是否需要关闭 FileInfo 对象?
- 是否有更合适的方法来轮换日志? (例如获取行数而不是字节大小的有效方法?)
【问题讨论】:
-
除非您使用 FileShare.ReadWrite,否则您通常无法打开该文件。 File.ReadLines() 没有,你需要code like this。实现滚动日志文件的最佳方式不是自己动手,而是使用库,例如 NLog。