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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With