The FileSystemWatcher component in Visual Studio .NET allows you to respond to file system changes. It's very handy whenever you need to perform a certain action in response to a file being updated.
FileSystemWatcher is a component in Visual Studio .NET that allows you to respond to file system changes. It's very handy whenever you need to perform a certain action in response to a file being updated and in numerous other situations.
Using FileSystemWatcher in your app
In order to add FileSystemWatcher to your Windows application, click on a Toolbox and find FileSystemWatcher under the list's Components section. Double-click FileSystemWatcher, and then the component will be visible under the Windows form (by default, it will be FileSystemWatcher1).
Now you are ready to set the properties of FileSystemWatcher1. This is how I set the following properties of the control through the Properties window in our example:
- Filter: abc.txt
- NotifyFilter: LastAccess
- Path: C:\temp
Then I double-click FileSystemWatcher1 and add the following code to its Changed event:
In order to get the example to work, you need to create a file in your c:/temp directory called abc.txt since the code assumes you already have this file. Then start your Windows application and — while it's running — open, edit, save, and close abc.txt. You should see the message box show up stating the file has changed. If you open the file but you don't save any changes to it, you will not see the message box since the NotifyFilter stated Write but not Open. In order to watch for changes in a particular directory, you would have to change the Filter property and the NotifyFilter property accordingly.
Irina Medvinskaya has been involved in technology since 1996. She has an MBA from Pace University and works as a project manager at Citigroup.
————————————————————————————————————————————Get Visual Basic tips in your inbox
Advance your scripting skills to the next level with TechRepublic's free Visual Basic newsletter, delivered each Friday. Automatically subscribe today!