使用 C# 从文本文件中读取最后一个符号

Ksi*_*ice 4 c# file-io

使用 C# 读取大型文本文件的最后一个符号或行的最有效方法是什么?

Dou*_*las 5

假设您的文本文件是 ASCII,此方法将允许您直接跳转到最后一个字符并避免阅读文件的其余部分(就像目前给出的所有其他答案一样)。

using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    stream.Seek(-1, SeekOrigin.End);
    byte b = (byte)stream.ReadByte();
    char c = (char)b;
}
Run Code Online (Sandbox Code Playgroud)

如果您的程序需要处理多字节编码,您可能需要执行一些复杂的逻辑,如Skeet's answer所示。但是,鉴于您的情况仅限于读取最后一个字符,您可以实现特定于您预期编码的简化版本。下面的代码适用于 UTF-8(这是当今最流行的编码)。该Seek可登陆你的读者在前面的字符的中间,但解码器将从此被读取的最后一个字符的时间恢复。

FileInfo fileInfo = new FileInfo(path);
int maxBytesPerChar = Encoding.UTF8.GetMaxByteCount(1);
int readLength = Math.Min(maxBytesPerChar, (int)fileInfo.Length);

using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
{
    reader.DiscardBufferedData();
    reader.BaseStream.Seek(-readLength, SeekOrigin.End);

    string s = reader.ReadToEnd();
    char c = s.Last();
}
Run Code Online (Sandbox Code Playgroud)