C# Using File System Watcher to Monitor File Changes

Hello, C# developers! In this post, we’ll explore how to use the FileSystemWatcher class to monitor file system changes in C#. This feature is particularly useful for applications that need to track the state of files or directories, such as backup tools, logging applications, or any system that needs to be alerted to changes in the filesystem.

What is FileSystemWatcher?

The FileSystemWatcher class provides a way to listen for changes to the file system, such as file creations, deletions, modifications, and renames. You can use this to automatically execute actions in response to these changes. It’s available in the System.IO namespace.

Setting Up a FileSystemWatcher

Let’s set up a simple FileSystemWatcher to monitor a specific directory for changes. Here’s how:

using System;
using System.IO;

public class Program
{
    public static void Main(string[] args)
    {
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.Path = @"C:\path\to\directory"; // Set the path to monitor

            // Watch for changes in LastAccess and LastWrite times, and the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;

            // Only watch text files.
            watcher.Filter = "*.txt";

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            Console.WriteLine("Press 'q' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }

    private static void OnChanged(object sender, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
        Console.WriteLine($"File: {e.FullPath} {e.ChangeType}");
    }

    private static void OnRenamed(object sender, RenamedEventArgs e)
    {
        // Specify what is done when a file is renamed.
        Console.WriteLine($"File: {e.OldFullPath} renamed to {e.FullPath}");
    }
}

This code sets up a FileSystemWatcher to monitor a specified directory for changes to text files. It handles file changes, creations, deletions, and renames by attaching event handlers and displays appropriate messages when these events occur.

Running the Watcher

Compile the application and run it. Try creating, editing, or deleting text files in the specified directory while the application is running. The console will output messages reflecting the changes made.

Handling Multiple Events

You can handle multiple events by adding additional methods or using a single method that checks the event type. The important events you can listen for include:

  • Changed: Occurs when a file is changed.
  • Created: Occurs when a new file is created.
  • Deleted: Occurs when a file is deleted.
  • Renamed: Occurs when a file is renamed.

Best Practices for FileSystemWatcher

  • Use a Full Path: Always set the watcher path to an absolute path to avoid issues with relative paths.
  • Optimize Performance: Limit the NotifyFilter to only those properties you need to watch.
  • Handle Exceptions: Implement error handling, as file changes can occur quickly and may lead to exceptions if not managed correctly.

Conclusion

The FileSystemWatcher class provides an effective way to monitor and respond to changes in the file system using C#. By implementing a file watcher, you can create useful applications that respond to file activities in real-time. Start using FileSystemWatcher in your applications to enhance their capabilities!

To learn more about ITER Academy, visit our website. Visit Here

Scroll to Top