且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用FileSystemWatcher从文件中获取新行

更新时间:2023-12-04 14:15:28

如果它是一个日志,文件大小和更改:

  using(FileStream fs = new FileStream(t.log,FileAccess.Read))
{
fsSeek(previousSize,SeekOrigin.Begin);
//读取,显示,...
PreviousSize = fs.Length;
}


I'm watching a file with the following code:

        [..]
        FileSystemWatcher watcher = new FileSystemWatcher();
        watcher.Path = @"C:\";
        watcher.Filter = "t.log";
        watcher.Changed += new FileSystemEventHandler(watcher_Changed);
        watcher.EnableRaisingEvents = true;

        private static void watcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("Changed!");
        }
        [..]

This works. Now, supposed that the content if file t.log is:

row 1
row 2
row 3
row 4

When I add to the file (and save) a couple of lines and the file becomes this:

row 1
row 2
row 3
row 4
row 5
row 6

How can I retrieve that the added lines are "row 5" and "row 6"?

Mind that the file may be very large, so having its content in memory and making a diff with the new version is not an option. Similarly, storing the value of the last read line and count from that on is not possible too, as it would force me to read the whole file every time, plus there may be lines with the same value.

Any help really appreciated.

If it's a log, always appended, you can keep the file size and on change :

using (FileStream fs = new FileStream("t.log", FileAccess.Read))
{
  fs.Seek(previousSize, SeekOrigin.Begin);
  //read, display, ...
  previousSize = fs.Length;
}