如何截断一个文件到一定的规模,但保持了端部? [英] How to truncate a file down to certain size but keep the end section?

查看:126
本文介绍了如何截断一个文件到一定的规模,但保持了端部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有多数民众赞成追加到随着时间的推移一个文本文件,并定期我想截断下来到一定规模,如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);
    }
}

这篇关于如何截断一个文件到一定的规模,但保持了端部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆