System.IO.IOException C # when FileInfo and WriteAllLines

I want to clear some volume of my text log file if it is larger than max:

FileInfo f = new FileInfo(filename);
if (f.Length > 30*1024*1024)
{
    var lines = File.ReadLines(filename).Skip(10000);
    File.WriteAllLines(filename, lines);
}

But I have an exception

System.IO.IOException: The process cannot access the file '<path>' because it is being used by another process.

Questions:

  • Do I need to close the FileInfo object before future work with the file?
  • Is there an even more suitable method for turning logs? (e.g. an eficciant way to get the number of rows instead of the byte size?)
+4
source share
1 answer

File.ReadLineskeep the file open until you delete the returned one IEnumerable<string>.

So this has nothing to do with FileInfo.

If you need to write it back to the same file, completely list the contents:

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

" ", ? . , "" ( - , , , 1 , , 100 000 ..), , .

, , .

+3

Source: https://habr.com/ru/post/1607145/


All Articles