加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 如何读取最后一个“n”行的日志文件

发布时间:2020-12-15 03:45:48 所属栏目:百科 来源:网络整理
导读:需要一段代码,可以读出日志文件的最后一行“n行”.我从网上提出了以下代码.我对C sharp有点新鲜.由于日志文件可能是 相当大,我想避免阅读整个文件的开销.有人建议任何性能提升.我真的不想读每个字符并改变位置. var reader = new StreamReader(filePath,Enco
需要一段代码,可以读出日志文件的最后一行“n行”.我从网上提出了以下代码.我对C sharp有点新鲜.由于日志文件可能是
相当大,我想避免阅读整个文件的开销.有人建议任何性能提升.我真的不想读每个字符并改变位置.
var reader = new StreamReader(filePath,Encoding.ASCII);
            reader.BaseStream.Seek(0,SeekOrigin.End);
            var count = 0;
            while (count <= tailCount)
            {
                if (reader.BaseStream.Position <= 0) break;
                reader.BaseStream.Position--;
                int c = reader.Read();
                if (reader.BaseStream.Position <= 0) break;
                reader.BaseStream.Position--;
                if (c == 'n')
                {
                    ++count;
                }
            }

            var str = reader.ReadToEnd();

解决方法

您的代码将执行得很差,因为您不允许任何缓存发生.
另外,对于Unicode来说,它根本不起作用.

我写了以下实现:

///<summary>Returns the end of a text reader.</summary>
///<param name="reader">The reader to read from.</param>
///<param name="lineCount">The number of lines to return.</param>
///<returns>The last lneCount lines from the reader.</returns>
public static string[] Tail(this TextReader reader,int lineCount) {
    var buffer = new List<string>(lineCount);
    string line;
    for (int i = 0; i < lineCount; i++) {
        line = reader.ReadLine();
        if (line == null) return buffer.ToArray();
        buffer.Add(line);
    }

    int lastLine = lineCount - 1;           //The index of the last line read from the buffer.  Everything > this index was read earlier than everything <= this indes

    while (null != (line = reader.ReadLine())) {
        lastLine++;
        if (lastLine == lineCount) lastLine = 0;
        buffer[lastLine] = line;
    }

    if (lastLine == lineCount - 1) return buffer.ToArray();
    var retVal = new string[lineCount];
    buffer.CopyTo(lastLine + 1,retVal,lineCount - lastLine - 1);
    buffer.CopyTo(0,lineCount - lastLine - 1,lastLine + 1);
    return retVal;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读