Language: EN

csharp-directory-watcher

Detect changes in files and directories in C# DirectoryWatcher

The C# DirectoryWatcher library is a high-performance Open Source implementation that allows us to detect real-time changes in files and directories.

This library is an alternative to the .NET FileSystemWatcher class. So DirectoryWatcher makes significant improvements to certain limitations of the native library.

The first difference is that the native class only reports file modifications. While DirectoryWatcher notifies of events occurring in both files and folders.

Specifically, the events that we can subscribe to with DirectoryWatcher are the following.

  • Renamed file or folder
  • Deleted file or folder
  • Created file or folder

Another important improvement is that DirectoryWatcher tries to eliminate duplicate events. While the FileSystemWatcher tends to generate the same event multiple times (especially in deletion).

In addition, DirectoryWatcher better handles exceptions and errors, since the native system is prone to errors that completely close the application.

Finally, DirectoryWatcher better handles large units or volumes, supports UNC/Unix files. In general, it is much more efficient and robust than the native method.

How to use DirectoryWatcher

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package MyOddWeb.DirectoryWatcher

Using “DirectoryWatcher” is quite simple. 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 manage, such as Changed, Created, Deleted, and Renamed.

DirectoryWatcher is Open Source, and all the code and documentation is available in the project’s repository on GitHub - FFMG/myoddweb.directorywatcher