Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting new lines from a file with FileSystemWatcher

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.

like image 222
pistacchio Avatar asked Jul 29 '09 08:07

pistacchio


1 Answers

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;
}
like image 165
Guillaume Avatar answered Oct 16 '22 14:10

Guillaume