File/Directory Monitoring
The FileSystemWatcher class is designed to monitor and report when changes occur in or to a directory. The FileSystemWatcher class is a part of the System.IO namespace.
I will be using the System.Diagnostics namespace to write to the debug window in this tutorial.
To begin we need to create a new FileSystemWatcher:
FileSystemWatcher SysWatch = new FileSystemWatcher(); |
Then we need to define some of the properties:
//This is the directory that will be monitored SysWatch.Path = "C:\\WatchedFolder"; //Watch only text files SysWatch.Filter = "*.txt"; //Monitor the file name changes SysWatch.NotifyFilter = NotifyFilters.FileName; //Setup the created and renamed event handlers SysWatch.Created += new FileSystemEventHandler(FolderMonitor_Created); SysWatch.Renamed += new RenamedEventHandler(FolderMonitor_Renamed); //Begin watching the folder SysWatch.EnableRaisingEvents = true; |
Everything above should be self explanatory, although I will expand on the filters. There are various types of filters we could apply:
//Only monitor files that start with "tmp" and have the .dat extention. EG: temp001.dat SysWatch.Filter = "tmp*.dat"; //Monitor all files SysWatch.Filter = "*.*"; //Only monitor Data.rtf SysWatch.Filter = "Data.rtf"; |
Here are the event handlers:
void FolderMonitor_Renamed(object sender, RenamedEventArgs e) { Debug.WriteLine(e.Name + " " + e.ChangeType + ": " + DateTime.Now.ToShortTimeString()); } void FolderMonitor_Created(object sender, FileSystemEventArgs e) { Debug.WriteLine(e.Name + " " + e.ChangeType + ": " + DateTime.Now.ToShortTimeString()); } |
The code in the event handlers could be applied to the other watches as well. As they output the name of the file, what change has occured and the time when they occured. Here is an example output in the debug window:
New Text Document.txt Created: 3:44 PM |
When we are finished monitoring we can stop the monitor:
SysWatch.EnableRaisingEvents = false; |
Warnings
- Ensure you have the correct permissions before attempting to monitor a directory.
- The events are fired as soon as they happen. So, for example, if you wish to process a file when it is moved into a directory and you attempt to do so as soon as the event is fired it may not work as the whole file may not have been moved yet.