如何截断一个文件到一定的规模,但保持了端部?规模、文件、到一定

2023-09-04 08:26:00 作者:终于成了单身狗

我有多数民众赞成追加到随着时间的推移一个文本文件,并定期我想截断下来到一定规模,如10MB,但保持最后10MB,而不是第一个。

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.

有什么聪明的方法来做到这一点?我猜我应该寻求正确的点,从那里读入一个新的文件,删除旧文件并重新命名新文件到旧名称。更好的想法或例如code?理想情况下我也不会读取整个文件到内存,因为该文件可能是很大的。

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.

请使用log4net的任何建议等。

Please no suggestions on using Log4Net etc.

推荐答案

如果你没问题,光看过去的10MB内存,这应该工作:

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.CopyTo(s);
    }
}