如何有效地只读取文本文件的最后一行

时间:2012-05-02 08:12:14

标签: c# file stream

需要从大日志文件中获取最后一行。最好的方法是什么?

3 个答案:

答案 0 :(得分:14)

您想使用ReverseLineReader向后阅读文件:

How to read a text file reversely with iterator in C#

然后在其上运行.Take(1)

var lines = new ReverseLineReader(filename);
var last = lines.Take(1);

您希望直接使用Jon Skeet'sMiscUtil,而不是复制/粘贴代码。

答案 1 :(得分:2)

    String lastline="";
    String filedata;

    // Open file to read
    var fullfiledata = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader sr = new StreamReader(fullfiledata);

    //long offset = sr.BaseStream.Length - ((sr.BaseStream.Length * lengthWeNeed) / 100);
    // Assuming a line doesnt have more than 500 characters, else use above formula
    long offset = sr.BaseStream.Length - 500;

    //directly move the last 500th position
    sr.BaseStream.Seek(offset, SeekOrigin.Begin);

    //From there read lines, not whole file
    while (!sr.EndOfStream)
    {
        filedata = sr.ReadLine();
        // Interate to see last line
        if (sr.Peek() == -1)
        {
            lastline = filedata;
        }
    }       

    return lastline;
}

答案 2 :(得分:-2)

或者你可以做两行(仅限.Net 4)

var lines = File.ReadLines(path);
string line = lines.Last();