Link to home
Start Free TrialLog in
Avatar of ajny
ajny

asked on

How to monitor changes in file content?

Hi,

I need to write a simple(?) component that will monitor the changes being made to a text file and notify them to registered listeners.

I have a process which writes data to a text file in the following way:

Start
... //data
End
Start
...//data
End
...
etc

I want to monitor the file and get notified when certain lines are written (e.g. Start/End).

A quick google search yielded the FileSystemWatcher class but I don't think it fits since it only monitors file system events and not file content, but I could be wrong as I'm fairly new to C#/.NET.

Thanks for any help.

ASKER CERTIFIED SOLUTION
Avatar of Colemss
Colemss
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ajny
ajny

ASKER

Hi Colemss,

Thanks for your quick reply!

I was hoping there's a better solution.

As I wrote, I'm already aware of the FileSystemWatcher class and its usages.
What I'm trying to write is a generic file watcher that can detect an arbitrary pattern (regex) being written to a file.

Using FileSystemWatcher will force me to re-read the file every time or (more likely) to keep track of where I stopped the last time and seek to that location before the next search.
Although these approaches will work, I was hoping there's a way to hook the monitor on the write operation (in a sense like a filter), so it can "see" what's about to be written to the file.
The only way I can imagine doing this would be with some sort of system hook.  It would require win32 dll hooks.  Most likely you will find c++ examples.  These would be undocumented Microsoft core hooks.  Unless this is  a major deal its probably not worth doing.  I have never seen any examples of looking at the data before or during a file write. It would be interesting.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That is the full source to my first suggestion.  I would try it. But it is using FileSystemWatcher.
He has to use a timer or a filesystemwatcher to monitor changes. I believe a filesystemwatcher will have a better performance.
Avatar of ajny

ASKER

Thanks for your help, guys.

I'll wait a little while to see if someone can come up with a better solution before I resort to FileSystemWatcher.