【问题标题】:How to read a log file which is hourly updated in c#?如何读取在 C# 中每小时更新的日志文件?
【发布时间】:2015-09-09 08:38:49
【问题描述】:

我正在尝试用 C# 编写一个读取日志文件的控制台应用程序。我面临的问题是该日志文件每 1 小时更新一次,因此例如,如果我在开始时有 10 行,之后有 12 行,那么在我的第二次读取尝试中,我将只需要读取 2 行新添加的行。 您能否建议我一种有效地执行此操作的方法(无需再次读取所有行,因为日志文件通常有 5000 多行)?

【问题讨论】:

  • 如果我正确理解您的问题,您可以尝试以下操作:var nextLines = File.ReadLines("filePath").Skip(lineCount);
  • @Sean 谢谢你的回答,我已经试过了,但是一个朋友告诉我它仍然会读取整个日志文件,所以在 5-10k 行的情况下可能不是这样高效。
  • 也许不是。我想这取决于文件的大小 - Garath 的回答也不错。

标签: c# loops logfile memory-efficient


【解决方案1】:

首先,您可以使用FileSystemWatcher 在文件更改后收到通知。

此外,您可以使用FileStreamSeek 函数仅准备新添加的行。在http://www.codeproject.com/Articles/7568/Tail-NET 上有一个Thread.Sleep 的例子:

using ( StreamReader reader = new StreamReader(new FileStream(fileName, 
                     FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) )
{
    //start at the end of the file
    long lastMaxOffset = reader.BaseStream.Length;

    while ( true )
    {
        System.Threading.Thread.Sleep(100);

        //if the file size has not changed, idle
        if ( reader.BaseStream.Length == lastMaxOffset )
            continue;

        //seek to the last max offset
        reader.BaseStream.Seek(lastMaxOffset, SeekOrigin.Begin);

        //read out of the file until the EOF
        string line = "";
        while ( (line = reader.ReadLine()) != null )
            Console.WriteLine(line);

        //update the last max offset
        lastMaxOffset = reader.BaseStream.Position;
    }
}

【讨论】:

  • 谢谢@Garath,您的解决方案对我很有用。我只是有一个问题。我使用 Console.WriteLine(lastMaxOffset) 来查看我会得到什么值,并且有一个数字,例如 1911。你能告诉我这个值代表什么吗?
  • 文件中的偏移量。所以下次文件流开始从这个值读取
猜你喜欢
  • 2021-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-19
  • 1970-01-01
  • 1970-01-01
  • 2011-03-10
  • 1970-01-01
相关资源
最近更新 更多