“Watching” a Directory for Changes
Directory “watching” is one of those really cool techniques that took quite a large
lump of skill to implement successfully in Visual Basic 6. With this latest version
of VB, however, you can get such functionality by utilizing the brand new
The new System.IO.FileSystemWatcherclass can be set up either in code or,
rather easier, by dragging and dropping the FileSystemWatcher component from
the toolbox Component tab onto your application.
Next, you need to start setting properties. First, there’s the Pathproperty,
which you need to set to the path of the directory that you wish to monitor, such
as “c:\” or “e:\whitecliff\”. Next, there’s the Filterproperty, where you specify
which files you want to monitor. You can use “*.*” to keep an eye on everything in
the directory, something like “*.doc” to check Word documents, or simply use an
exact filename, such as “datalog.txt”.
There’s also the NotifyFilterproperty, which lists exactly what you want
your FileSystemWatcherobject to inform you about. The default is “FileName,
DirectoryName, LastWrite,” which means that you’re informed when a filename
or directory name is changed, or a file is written (that is, the LastWrite date and
time changes). You can specify your own in code by typing the options from the
dropdown list, separated by commas, or in code using the bitwise “Or” operator.
Finally, there’s the IncludeSubdirectoriesproperty. Change this to Trueif you want
to monitor all subdirectories—or Falseotherwise.
And after you’ve set up your FileSystemWatcherobject? Simply respond to its
events (ensure that the EnableRaisingEventsproperty is set to True). You have the
Changed, Created, Deleted, and Renamedevents all at your disposal. Each will fire off
whenever a related action occurs. For example, if you’re monitoring “c:\mydata\”,
with a filter of “*.txt” and the default NotifyFilterproperty value, and your user or
an application edits the contents of “c:\mydata\test.txt”—the Changedevent will fire.
From within the event, you can use the “e” argument (the
System.IO.FileSystemEventArgsobject) to find out more about the altered file.
You may use the e.FullPathproperty to find out the filename, for example—or
analyze the ChangeTypeor Path.
TOP TIP P There’s an
Errorevent associated with the FileSystemWatchercom-
ponent,too.It only ever comes into play when far too many changes are being
made at once (typically a result of badly chosen properties,or mass file alter-
ations by the user) and the system just cannot cope.If it ever occurs,you’ll know
the events raised may not cover all items.Not always good to experience,but
certainly a great event to be aware of.
More .NET Secrets