So you want to watch a folder for file changes? So, why not use the built in .NET file watcher class? It's extremely easy to use and implement. Only one problem: every time you need this functionality, you tend to write all the code all over again. So I thought: why not wrap the file watcher functionality and then just reuse the wrapper class.
Design of the Wrapper Class
The wrapper class contains all that is needed to watch a folder for changes:
- it monitors changes / deletion / addition / renaming of files & folders
- a filter can be supplied to only monitor a certain group of files, e.g.: *.txt.
- you can start or stop the watcher on command.
The watcher also wraps the events fired by the .NET file watcher and fires a single event for all different types of file changes. This event uses the event arguments class:
FileWatcherEventArgs. This class contains the filename, path, old filename (for renaming), old path (for renaming) and a change type. The change type is useful for monitoring what type of change occurred. It is an
public enum fileWatcherChangeType
How to use the code
It's very easy. Add the file FileWatcher.cs to your project. Add the code "
using Utils;" and that's it! Here is an example of some form code of how to use the class:
private void button1_Click(object sender, System.EventArgs e)
Utils.FileWatcher fw = new Utils.FileWatcher(@"c:\test");
fw.Changed += new Utils.FileWatcher.ChangedEventHandler(showChange);
private void showChange(object source, Utils.FileWatcherEventArgs e)
MessageBox.Show(e.ChangeType.ToString() + " " + e.FileName);
There is also a public method
destroyWatcher which stops the current file watcher.
That's it! Very basic and easy to implement. Enjoy