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

.net, c#, text-files

Solution

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);
    }
}

Problem

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.

Original source