Retrieving new lines from a file using FileSystemWatcher

I am looking at 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!"); } [..] 

It works. Now suppose the content if the t.log file is:

 row 1 row 2 row 3 row 4 

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

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

How can I get the added lines to be "line 5" and "line 6"?

Remember that a file can be very large, so having its contents in memory and creating a difference from the new version is not an option. Similarly, saving the value of the last line of reading and counting from this point on is also impossible, since this would make me read the entire file every time, plus there may be lines with the same value.

Any help is really appreciated.

+4
source share
2 answers

If this is a log always added, you can save the file size and change:

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

The only thing I see can work when you add only lines. Then just save the number of lines.

0
source

All Articles