The FileSystemWatcher is a file system notification class. With this class, you can monitor a specific directory or file for changes, and be notified when the event occurs. In this article, we'll create a simple windows application that prints a message when text files in a specific path are accessed. The concepts presented here can be used for more complicated apps, such as a security monitoring tool for website changes, or perhaps an error handling procedure when an error log is written to the filesystem.
Setting up the FileSystemWatcher is simple. Typically, you will follow these steps:
- Instantiate the FileSystemWatcher
- Set the Path to monitor
- Set any Filters
- Set your event handler
The following code snippet shows the core of our sample application. As you can see, we first instantiate the FileSystemWatcher class in the System.IO namespace. Next we set the path to monitor, as well as the filters. Here, we are interested in text files being modified on the f: drive. We've defined an OnChanged method, and set this method as the EventHandler.
public Form1() { InitializeComponent(); System.IO.FileSystemWatcher watcher=new System.IO.FileSystemWatcher(); watcher.Path = "f:\\"; watcher.Filter ="*.txt"; watcher.NotifyFilter = System.IO.NotifyFilters.LastWrite; watcher.EnableRaisingEvents =true; watcher.Changed +=new System.IO.FileSystemEventHandler(OnChanged); } privatevoid OnChanged(objectsender, System.IO.FileSystemEventArgs e) { textBox1.Text += e.Name.ToString()+" changed at "+ System.DateTime.Now.ToString(); } PublicSubNew() MyBase.New()
InitializeComponent()
DimwatcherAsSystem.IO.FileSystemWatcher=NewSystem.IO.FileSystemWatcher() watcher.Path= "f:\" watcher.Filter="*.txt" watcher.NotifyFilter=System.IO.NotifyFilters.LastWrite watcher.EnableRaisingEvents=True
AddHandlerwatcher.Changed,AddressOfMe.OnChanged EndSub
PrivateSubOnChanged(ByValsenderAsObject,ByVal e AsSystem.IO.FileSystemEventArgs) TextBox1.Text+= e.Name.ToString()&" changed at "&System.DateTime.Now.ToString() EndSub | |
When an event is fired, we use the FileSystemEventArgs to get the name of the file triggering the event, and display a message to the screen noting the time we learned of the event. The screenshot below shows our application in action: