受这个答案的启发,我想知道如果使用大量的FileStream.Seek(-1)
会发生什么。
为了清晰起见,我将重新发布答案:
using (var fs = File.OpenRead(filePath))
{
fs.Seek(0, SeekOrigin.End);
int newLines = 0;
while (newLines < 3)
{
fs.Seek(-1, SeekOrigin.Current);
newLines += fs.ReadByte() == 13 ? 1 : 0; // look for \r
fs.Seek(-1, SeekOrigin.Current);
}
byte[] data = new byte[fs.Length - fs.Position];
fs.Read(data, 0, data.Length);
}
个人建议读取2048字节到缓冲区中,然后在缓冲区中查找该字符。
使用反编译工具Reflector我发现该方法内部使用了SetFilePointer。
关于Windows缓存和倒序读取文件的任何文档资料吗?当连续使用Seek(-1)
时,Windows是否会倒序缓存并查询缓存,还是会从当前位置向前读取?
值得注意的是,大多数人都认为Windows进行了良好的缓存,但是与此同时,“倒序读取文件”的每个答案都涉及读取字节块并对其进行处理。