views:

102

answers:

2

Hi,

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.

+4  A: 

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;
}
Guillaume
A: 

The only usecase I see it can work is when you're only adding lines. Then simply store number of lines.

Yakeen