The C# DirectoryWatcher library is a high-performance Open Source implementation that allows us to detect file and directory changes in real-time.
This library is an alternative to the .NET FileSystemWatcher class. Thus, DirectoryWatcher presents significant improvements over certain limitations of the native library.
The first difference is that the native class only reports modifications to files. While DirectoryWatcher notifies of events occurring in both files and folders.
Specifically, the events we can subscribe to with DirectoryWatcher are the following.
- File or folder renamed
- File or folder deleted
- File or folder created
Another major improvement is that DirectoryWatcher attempts to eliminate duplicate events. Whereas FileSystemWatcher often generates the same event multiple times (especially on deletion).
Furthermore, DirectoryWatcher handles exceptions and errors better, as the native system is prone to generating errors that completely crash your application.
Finally, DirectoryWatcher handles large drives or volumes better, supports UNC/Unix files. In general, it is considerably more efficient and robust than the native method.
How to Use DirectoryWatcher
We can easily add the library to a .NET project via the corresponding Nuget package.
Install-Package MyOddWeb.DirectoryWatcher
Using “DirectoryWatcher” is quite straightforward. You can create an instance of the DirectoryWatcher class and subscribe to the events you want to monitor.
using( var watch = new Watcher() )
{
watch.Add(new Request("C:\\Directory_to_monitor", true));
watch.Add(new Request("d:\\foo\\bar\\", true));
watch.Add(new Request("y:\\", true));
watcher.Changed += (sender, e) =>
{
Console.WriteLine($"File modified: {e.FullPath}");
};
watcher.Created += (sender, e) =>
{
Console.WriteLine($"File created: {e.FullPath}");
};
watcher.Deleted += (sender, e) =>
{
Console.WriteLine($"File deleted: {e.FullPath}");
};
watcher.Renamed += (sender, e) =>
{
Console.WriteLine($"File renamed: {e.OldFullPath} -> {e.FullPath}");
};
watcher.Error += (sender, e) =>
{
Console.WriteLine($"Error: {e.GetException().Message}");
};
watcher.Start();
In this example, we create an instance of DirectoryWatcher and specify the directory we want to monitor. Then, we subscribe to the different events we want to handle, such as Changed, Created, Deleted, and Renamed.
DirectoryWatcher is Open Source, and all the code and documentation is available in the project repository at GitHub - FFMG/myoddweb.directorywatcher

