Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate a file down to certain size but keep the end section?

I have a text file that's appended to over time and periodically I want to truncate it down to a certain size, e.g. 10MB, but keeping the last 10MB rather than the first.

Is there any clever way to do this? I'm guessing I should seek to the right point, read from there into a new file, delete old file and rename new file to old name. Any better ideas or example code? Ideally I wouldn't read the whole file into memory because the file could be big.

Please no suggestions on using Log4Net etc.

like image 565
Rory Avatar asked Jun 17 '12 15:06

Rory


People also ask

How do you cut a file size?

Remove unnecessary images, formatting and macros. Save the file as a recent Word version. Reduce the file size of the images before they are added to the document. If it is still too large, save the file as a PDF.

What does it mean to truncate a file?

To truncate is to shorten by cutting off. In computer terms, when information is truncated, it is ended abruptly at a certain spot. For example, if a program truncates a field containing the value of pi (3.14159265...) at four decimal places, the field would show 3.1415 as an answer.

How do you truncate a file in C#?

To truncate a file in C#, use the FileStream. SetLength method.


1 Answers

If you're okay with just reading the last 10MB into memory, this should work:

using(MemoryStream ms = new MemoryStream(10 * 1024 * 1024)) {
    using(FileStream s = new FileStream("yourFile.txt", FileMode.Open, FileAccess.ReadWrite)) {
        s.Seek(-10 * 1024 * 1024, SeekOrigin.End);
        s.CopyTo(ms);
        s.SetLength(10 * 1024 * 1024);
        s.Position = 0;
        ms.Position = 0; // Begin from the start of the memory stream
        ms.CopyTo(s);
    }
}
like image 191
Ry- Avatar answered Sep 29 '22 20:09

Ry-