【问题标题】:How to efficiently read only last line of the text file如何有效地只读取文本文件的最后一行
【发布时间】:2012-05-11 16:54:51
【问题描述】:

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

【问题讨论】:

    标签: c# file stream


    【解决方案1】:

    您想使用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,而不是复制/粘贴代码。

    【讨论】:

    • 不错!谢谢,会试试的。
    • 奇怪的是库不在 Nuget..谢谢!
    • 在可能重复的stackoverflow.com/a/33907602/4821032中查看我的答案
    • 我知道这个答案来自过去,但对于任何阅读这篇文章的人来说,按照 Jon Skeet 本人的说法,“你不会直接使用 Jon Skeet 的库”,而是复制/粘贴,采取什么你想从代码中。 github.com/jpsingleton/ANCLAFS/issues/6
    【解决方案2】:

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

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

    【讨论】:

    • 虽然这可以完成这项工作,但它的内存效率非常低(正如 RJFalconer 指出的那样)并且还有很大的延迟 - 请记住,读取文件是您在程序中可以做的最慢的事情之一.如果您只是不经常阅读,这可能会奏效,但这与强大的专业解决方案相去甚远
    【解决方案3】:
        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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 2012-07-22
      • 2011-02-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多