从上次读取位置读取日志文件

Read log file from last read position

这是我的工作代码,我有一个 filewatcher 监视我的日志文件,当文件更新(更新很多)时,它会读取日志并将符合正则表达式的行输出到文本框。它的问题是它从头读取文件并再次重新打印正则表达式行,所以我在文本框中得到重复的数据。我也不知道我是否已将其正确设置为 运行 从单独线程读取的文件,因此我的程序在读取大型日志文件时不会 "freeze"。

private void btnStart_Click(object sender, EventArgs e)
{
    if ((Properties.Settings.Default.setting_logfile != "") && (Properties.Settings.Default.setting_logfolder != ""))
    {
        if (btnStart.Text == "Start Parsing")
        {
            // change text on button and switch status image
            btnStart.Text = "Stop Parsing";
            pbStatus.Image = Properties.Resources.online;

            new Thread(() => Run()).Start();
        }
        else
        {
            btnStart.Text = "Start Parsing";
            pbStatus.Image = Properties.Resources.offline;
            fsWatcher.EnableRaisingEvents = false;
        }
    }
    else
    {
        tbOutput.Text = "Please select a log file to parse.";
    }
}

private void Run()
{
    try
    {
        fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
        fsWatcher.EnableRaisingEvents = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show("An error occurred: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

private void OnChanged(object source, FileSystemEventArgs e)
{
    string line;

    Regex pattern = new Regex(@"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");

    Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
    StreamReader streamReader = new StreamReader(stream);

    while ((line = streamReader.ReadLine()) != null)
    {
        Match match = pattern.Match(line);
        if (match.Success)
        {
            tbOutput.AppendText(line + "\r\n");
        }
    }
    streamReader.Close();
    stream.Close();
}

您可以记住您阅读的最后位置并从那里开始。

 Regex pattern = new Regex(@"\[[\w :]+\]\s<SYSTEMWIDE_MESSAGE>:");
 long lastPosition = 0;

 private void OnChanged(object source, FileSystemEventArgs e)
 {
   string line;


   Stream stream = File.Open(e.FullPath, FileMode.Open, FileAccess.Read,     FileShare.ReadWrite);
   stream.Seek(lastPosition, SeekOrigin.Begin);
   StreamReader streamReader = new StreamReader(stream);

   while ((line = streamReader.ReadLine()) != null)
   {
      if (pattern.Match(line).Success)
      {
        tbOutput.AppendText(line + Environment.NewLine);
      }
   }
   lastPosition = stream.Position;  // may need to subtract 1!!!
   streamReader.Close();
   stream.Close();
}