C# FileSystemWatcher

Summary: in this tutorial, you’ll learn how to use the C# FileSystemWatcher class to monitor changes to files or directories in real-time.

Introduction to the C# FileSystemWatcher class

C# FileSystemWatcher class allows you to monitor a specific directory or file for changes in real-time.

The FileSystemWatcher class provides you with events that you can subscribe to, such as Created, Deleted, Changed, and Renamed, and allows you to execute code that responds to these events.

In practice, you can use the FileSystemWatcher class in many applications, such as file synchronization, automated backups, and real-time data processing.

C# FileSystemWatcher example

The following example demonstrates how to use the FileSystemWatcher to monitor the text file created in the C:\temp directory:

using FileSystemWatcher watcher = new();

// specify the directory to monitor
watcher.Path = @"C:\temp";

// specify the file extension to monitor (optional) 
watcher.Filter = "*.txt";

watcher.Created += new FileSystemEventHandler(OnFileCreated);

watcher.EnableRaisingEvents = true;

static void OnFileCreated(object source, FileSystemEventArgs e)
{
    Console.WriteLine("File Created: {0}", e.FullPath);
}

Console.WriteLine($"Create a new file {watcher.Filter} in the {watcher.Path} to see the event handler.");
Console.WriteLine("Press the return key to quit.");
    
Console.ReadLine();Code language: C# (cs)

How it works.

First, create a new instance of the FileSystemWatcher class and specify the directory or file you want to monitor:

using var FileSystemWatcher watcher = new();

// specify the directory to monitor
watcher.Path = @"C:\temp";

// specify the file extension to monitor (optional) 
watcher.Filter = "*.txt"; Code language: C# (cs)

Next, subscribe to the events you want to respond to. For example, to handle the file creation event, you can do like this:

watcher.Created += new FileSystemEventHandler(OnFileCreated);Code language: C# (cs)

Third, define the event handler method that handles the Created event:

private static void OnFileCreated(object source, FileSystemEventArgs e)
{
    Console.WriteLine("File Created: {0}", e.FullPath);
}Code language: C# (cs)

Finally, start the FileSystemWatcher by setting the EnableRaisingEvents property to true:

watcher.EnableRaisingEvents = true;Code language: C# (cs)

From now on, the FileSystemWatcher will now monitor the C:\temp directory and raise the appropriate events when a new text file is created.

The following output shows if we copy two new text files to the C:\temp directory:

Create a new file *.txt in the C:\temp to see the event handler.
Press the return key to quit.
File Created: C:\temp\readme.txt
File Created: C:\temp\query.txtCode language: C# (cs)

Summary

  • Use the FileSystemWatcher class to monitor changes to files or directories in real-time.
Was this tutorial helpful ?