Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.IO.IOException C# when FileInfo and WriteAllLines

I want to clean some volume of my text log file if it size more then 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 exception

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

Questions:

  1. Do I need close FileInfo object before future work with file?
  2. Is there some more adequate method to rotate logs? (for example eficciant way to obtain number of lines instead of it byte size? )
like image 430
Ivan Borshchov Avatar asked Oct 20 '22 02:10

Ivan Borshchov


1 Answers

File.ReadLines keep the file open until you dispose of the returned IEnumerable<string>.

So this has nothing to do with FileInfo.

If you need to write it back to the same file, fully enumerate the contents:

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

You mention "rotating logs", have you considered rotating files instead? ie. write to a fixed file, when it gets "full" (by whatever criteria you deem full, like 1GB in size, one days worth of log entries, 100.000 lines, etc.), you rename the file and create a new, empty, one.

You would probably want to rename existing rotated files as well, so as to keep the number of rotated files low.

like image 150
Lasse V. Karlsen Avatar answered Oct 21 '22 22:10

Lasse V. Karlsen