How to efficiently read only last line of the text

2019-02-23 05:39发布

Need to get just last line from big log file. What is the best way to do that?

标签: c# file stream
3条回答
forever°为你锁心
2楼-- · 2019-02-23 05:53

Or you can do it two line (.Net 4 only)

var lines = File.ReadLines(path);
string line = lines.Last();
查看更多
姐就是有狂的资本
3楼-- · 2019-02-23 05:56
    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;
}
查看更多
爷、活的狠高调
4楼-- · 2019-02-23 06:09

You want to read the file backwards using ReverseLineReader:

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

Then run .Take(1) on it.

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

You'll want to use Jon Skeet's library MiscUtil directly rather than copying/pasting the code.

查看更多
登录 后发表回答