How to use FileSystemWatcher in C#

By FoxLearn 1/7/2025 8:21:45 AM   85
The FileSystemWatcher class in the System.IO namespace is used to monitor changes in the file system.

It watches a specified directory or file for changes and triggers events when such changes occur.

The key events it raises are:

  • Changed: Triggered when a file or directory is modified.
  • Created: Triggered when a file or directory is created.
  • Deleted: Triggered when a file or directory is deleted.
  • Error: Triggered when an error occurs due to changes in the monitored path.
  • Renamed: Triggered when a file or directory is renamed.

To use FileSystemWatcher, you must specify the directory to monitor.

Creating a simple file system watcher in C#

Let's walk through an example of how to create a simple file system watcher in C#. In this case, we'll use a console application to monitor a directory for changes.

static void Main(string[] args)
{
    string path = @"C:\MyDirectory";  // Specify the directory you want to monitor
    MonitorDirectory(path);
    Console.ReadKey();  // Keeps the console open
}

Now, let’s look at how the MonitorDirectory method works. This method will monitor the specified directory for changes and trigger events when changes occur:

private static void MonitorDirectory(string path)
{
    FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
    fileSystemWatcher.Path = path;  // Set the directory path to monitor
    fileSystemWatcher.Created += FileSystemWatcher_Created;  // Event when a file is created
    fileSystemWatcher.Renamed += FileSystemWatcher_Renamed;  // Event when a file is renamed
    fileSystemWatcher.Deleted += FileSystemWatcher_Deleted;  // Event when a file is deleted
    fileSystemWatcher.EnableRaisingEvents = true;  // Enable event raising for changes
}

The EnableRaisingEvents property is set to true to start the monitoring process. This will ensure that the appropriate event handlers are triggered when there are changes in the directory.

For each event (Created, Renamed, Deleted), you'll need to create an event handler.

private static void FileSystemWatcher_Created(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File created: {0}", e.Name);
}

private static void FileSystemWatcher_Renamed(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File renamed: {0}", e.Name);
}

private static void FileSystemWatcher_Deleted(object sender, FileSystemEventArgs e)
{
    Console.WriteLine("File deleted: {0}", e.Name);
}

Assuming there is a directory named MyDirectory on your C: drive, run the console application.

When you create, rename, or delete files in that directory, the events will trigger and the file actions will be displayed in the console.