Monday, May 25, 2009

FileSystemWatcher

I recently came across the interesting FileSystemWatcher class in the .NET Framework. It's pretty cool; the class will watch a folder, and raise events when there are changes to the files in that folder. You can specify a filter (like "*.txt") to only watch for certain files, and react when files are created, deleted, and modified.

It's pretty easy to come up with possible uses for this class. Maybe you have an old process somewhere that produces data files at irregular intervals; you could watch the output folder, and immediately act whenever one of those files is added. You could create a kind of auto-publishing system; let your users know that any file they save in a certain folder will automatically be posted for them. You could set up a mechanism for communicating between processes.

This last one is something that I've seen done before in VFP. A timer is set up to repeatedly check a certain location for a "message" file from another process, and then the app can react accordingly. A FileSystemWatcher makes this kind of setup simple - just set properties specifying the files to look for, and the file system events to watch.

Implementing this is straightforward as well. Create an instance of the class:

FileSystemWatcher fsw = new FileSystemWatcher();

Set its properties, and hook up an event handler:

fsw.Path = "C:\\SomeFolder\\WatchFolder\\";
fsw.Filter = "*.txt";
fsw.NotifyFilter = NotifyFilters.LastWrite;
fsw.Changed += new FileSystemEventHandler(this.OnFileChange);


Write the handler to do the work:

private void OnFileChange(object source, FileSystemEventArgs e)
{
// ...
}

2 comments:

  1. Hi Rob,

    no need to revert to a NET class here, since such stuff is of course built into VFP9 already. It's called BINDEVENTS() and you can bind to Windows Shell-events. Start the Solution.app, and run the sample in "New in VFP9" / "Binding to Windows Message Events".

    wOOdy

    ReplyDelete
  2. Hi Woody,

    Yes you're right, in recent VFP BindEvents() could be used for this type of thing; I mentioned the timer approach for VFP that I recalled seeing used in older VFP versions. In my case where I came across the .NET FileSystemWatcher class, I was already working in C# so it made sense to use.

    Thanks!

    - Rob

    ReplyDelete