System.IO.IOException C# when FileInfo and WriteAllLines

本文关键字:FileInfo and WriteAllLines when IO IOException System | 更新日期: 2023-09-27 18:12:35

我想清理我的文本日志文件的一些体积,如果它的大小大于max:

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.

问题:

  1. 在将来使用文件工作之前,我需要关闭FileInfo对象吗?
  2. 是否有更合适的方法来旋转日志?(例如,获取行数而不是字节大小的有效方法?)

System.IO.IOException C# when FileInfo and WriteAllLines

File.ReadLines保持文件打开,直到处理返回的IEnumerable<string>

所以这与FileInfo无关。

如果您需要将其写回同一个文件,请完整枚举其内容:

var lines = File.ReadLines(filename).Skip(10000).ToList();

你提到"旋转日志",你考虑过旋转文件吗?ie。写入一个固定的文件,当它"满"时(根据您认为满的任何标准,如1GB大小,一天的日志条目,100,000行等),您将重命名该文件并创建一个新的空文件。

您可能还想重命名现有的旋转文件,以便保持低旋转文件的数量。