C#, Microsoft Windows

Monitor Directory for Changes

FileSystemWatcher is a class in .Net that listens to the file system change notifications and raises events when a directory, or file in a directory, changes.

You can monitor a single file or a directory for changes and get notified about those changes.

With FileSystemWatcher class you can monitor for new files creation, files editing, files deletion and files renaming.

Let’s see a simple example:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
private void monitor(String path, String extension)
{
	FileSystemWatcher watcher = new FileSystemWatcher();
	watcher.Path = path;
	watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
	watcher.Filter = extension;
	watcher.Changed += new FileSystemEventHandler(OnChanged);
	watcher.Created += new FileSystemEventHandler(OnCreated);
	watcher.Deleted += new FileSystemEventHandler(OnDeleted);
	watcher.Renamed += new RenamedEventHandler(OnRenamed);
	watcher.EnableRaisingEvents = true;
}
 
private static void OnChanged(object source, FileSystemEventArgs e)
{
	MessageBox.Show("A text file has been changed: " + e.FullPath + " " + e.ChangeType + ".");
}
 
private static void OnCreated(object source, FileSystemEventArgs e)
{
	MessageBox.Show("A text file has been created: " + e.FullPath + " " + e.ChangeType + ".");
}
 
private static void OnDeleted(object source, FileSystemEventArgs e)
{
	MessageBox.Show("A text file has been deleted: " + e.FullPath + " " + e.ChangeType + ".");
}
 
private static void OnRenamed(object source, RenamedEventArgs e)
{
	MessageBox.Show(String.Format("A text file has been renamed: {0} renamed to {1}.", e.OldFullPath, e.FullPath));
}

To use it, execute the following line of code in a button click event to watch for txt files changes:

//change the path accordingly
monitor(@"c:pathtodirectory", "*.txt");