The .NET Framework makes it easy to monitor file system changes--the FileSystemWatcher class can raise events when you create, delete, modify, or rename files in the folders that it's "watching". This sample demonstrates the properties exposed by the class, and allows you to interactively try out the various events.
The sample form allows you to set properties of the FileSystemWatcher object used by the demonstration, including:
Selecting the Enable Raising Events button turns on event handling for the FileSystemWatcher object, and event handlers in the form's class will write items to the list box on the form as you change files in the selected path. To make it easier to demonstrate, you can use the Create/Rename/Modify/Delete Sample File buttons on the form. These buttons create temporary files in the selected folder. (Use the Delete All Sample Files button to clean up all remaining sample files when you're done.)
You can also use Windows Explorer or any other application to create, modify, rename, and delete files. The sample application will still display the notifications, since the FileSystemWatcher object simply monitors for changes, without regard to the source application.
Requires the Trial or Release version of Visual Studio .NET Professional (or greater).
Although this sample application uses the FileSystemWatcher component (from the Components tab on the Toolbox), this isn't required. This does make it simpler to set properties at design time, but offers no real benefits beyond that. Adding the component to a form rather than using a normal instance of the object in code makes no difference in the code, except that you can set properties at design time, and the designer takes care of creating the variable and setting its properties in code. If you want to bypass the component, and do it all in code, you'd only need to delete the item from the form, and add to the class:
Private WithEvents fsw As New FileSystemWatcher()
You'll find only three event handlers in the class, although the FileSystemWatcher class raises five events. Because the Created, Changed, and Deleted events all share the same event signature, one event handler manages them all. The Renamed and Error events each have their own handlers, because their event signatures are slightly different.
In addition, a large block of code in the sample deals with using a CheckedListBox control to display the one or more bit-mask values in the NotifyFilter property. If you're interested in displaying enumerated values, allowing users to select one or more, and then applying the values back into a property that accepts an enumerated value, check out the code. The GetChecks and SetChecks procedures are basically generic--you should be able to pick them up and use them elsewhere, as long as you add items to the control as we've done here.