MrMAG
MrMAG

Reputation: 1264

Reading the last changes of a text file after FileSystemWatcher detects change

Relating to my earlier post: Smartest way to monitor log-files in realtime?
I want a FileSystemWatcher to detect changes of a text file (logfile) and afterwards I want it to show me the latest changes!

They are big files >50bm, and a full scan almost every second is very time-consuming.
I though .last() could help, but this code only returns the last row:

 File.ReadText(@"C:\Filename.txt").Last();

I need some code that can continue reading from the last spot and just determine and returns the changes.

Upvotes: 0

Views: 1724

Answers (2)

evanmcdonnal
evanmcdonnal

Reputation: 48134

FileSystemWatcher won't exactly do what you want. It sees changes at the directory level. Once the file changes it has no history of it's previous contents. Calling Last() on File.ReadText() also has no concept of the files previous state which is why it just returns the last row.

I think the best approach would be to save the EOF's position then each time the FSW raises a file changed event you would read from previous EOF position to the new EOF then update the variable which stores the EOF's position.

Upvotes: 1

ken2k
ken2k

Reputation: 49013

If you're only appending data at the end of the file, you could save in memory the position of the last read byte, and read from this position to the end of the file each time you're notified the file has been updated.

Upvotes: 1

Related Questions