ZetCode

C# FileSystemWatcher

last modified November 6, 2026

In this article we show how to monitor changes in the file system with the FileSystemWatcher class in C#.

FileSystemWatcher from the System.IO namespace raises events when files or directories in a watched directory are created, changed, renamed, or deleted. It uses the notification mechanism of the operating system: ReadDirectoryChangesW on Windows, inotify on Linux, and FSEvents on macOS. Typical uses are reloading a configuration file, processing files dropped into an inbox directory, and live reloading in development tools.

The events are raised on thread pool threads, not on the thread that created the watcher. The number and order of events for one operation depend on the operating system and on how the program that changes the file writes it.

Each example watches a demo directory, changes files in it itself, and deletes the directory at the end. The outputs come from Linux.

Basic example

The first example prints the events for a file that is created, extended, renamed, and deleted.

Program.cs
string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

using var watcher = new FileSystemWatcher(dir);

watcher.Created += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.Name}");
watcher.Changed += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.Name}");
watcher.Deleted += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.Name}");
watcher.Renamed += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.OldName} -> {e.Name}");

watcher.EnableRaisingEvents = true;

string file = Path.Combine(dir, "notes.txt");

Step(() => File.WriteAllText(file, "first line\n"));
Step(() => File.AppendAllText(file, "second line\n"));
Step(() => File.Move(file, Path.Combine(dir, "notes-old.txt")));
Step(() => File.Delete(Path.Combine(dir, "notes-old.txt")));

watcher.Dispose();
Directory.Delete(dir, true);

static void Step(Action action)
{
    action();
    Thread.Sleep(200);
}

We create a watcher for the demo directory and subscribe to its four events.

using var watcher = new FileSystemWatcher(dir);

The constructor takes the path of the directory to watch. By default, the watcher reports changes to file names, directory names, and the last write time, for all files in the directory but not in subdirectories.

watcher.Renamed += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.OldName} -> {e.Name}");

The Renamed event receives RenamedEventArgs, which also contain the old name.

watcher.EnableRaisingEvents = true;

The watcher starts reporting events only after EnableRaisingEvents is set to true.

action();
Thread.Sleep(200);

After each operation we wait a moment, so that the event arrives before the next operation. A single write raises several Changed events, because creating, writing, and closing a file are separate steps for the operating system. Their number varies from run to run, so the code must not depend on it.

$ dotnet run
Created: notes.txt
Changed: notes.txt
Changed: notes.txt
Renamed: notes.txt -> notes-old.txt
Deleted: notes-old.txt

Filtering by file name

The Filter property and the Filters collection limit the events to files that match wildcard patterns.

Program.cs
string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

using var watcher = new FileSystemWatcher(dir)
{
    NotifyFilter = NotifyFilters.FileName,
};

watcher.Filters.Add("*.csv");
watcher.Filters.Add("*.json");

watcher.Created += (s, e) => Console.WriteLine($"new data file: {e.Name}");
watcher.EnableRaisingEvents = true;

foreach (string name in new[] { "sales.csv", "readme.txt", "config.json", "image.png", "users.csv" })
{
    File.WriteAllText(Path.Combine(dir, name), "");
    Thread.Sleep(100);
}

Thread.Sleep(200);
watcher.Dispose();
Directory.Delete(dir, true);

We watch for new CSV and JSON files and ignore the others.

NotifyFilter = NotifyFilters.FileName,

With only FileName in the notify filter, the watcher reports file creation, deletion, and renaming, but not writes.

watcher.Filters.Add("*.csv");
watcher.Filters.Add("*.json");

The Filters collection, added in .NET Core 3.0, holds several patterns. The older Filter property takes a single pattern. The filtering is done by .NET after receiving the notifications, so it does not make the watcher cheaper.

$ dotnet run
new data file: sales.csv
new data file: config.json
new data file: users.csv

Notify filters

The NotifyFilter property selects which kinds of changes are reported. It is a combination of NotifyFilters flags such as FileName, DirectoryName, Attributes, Size, LastWrite, LastAccess, CreationTime, and Security.

Program.cs
string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);
string file = Path.Combine(dir, "data.txt");
File.WriteAllText(file, "");

using var watcher = new FileSystemWatcher(dir)
{
    NotifyFilter = NotifyFilters.Size,
};

watcher.Created += (s, e) => Console.WriteLine($"Created: {e.Name}");
watcher.Changed += (s, e) => Console.WriteLine($"Changed: {e.Name}");
watcher.Deleted += (s, e) => Console.WriteLine($"Deleted: {e.Name}");
watcher.EnableRaisingEvents = true;

Console.WriteLine("touch");
File.SetLastWriteTime(file, DateTime.Now.AddHours(-1));
Thread.Sleep(200);

Console.WriteLine("append");
File.AppendAllText(file, "new data");
Thread.Sleep(200);

Console.WriteLine("create and delete another file");
File.WriteAllText(Path.Combine(dir, "other.txt"), "");
File.Delete(Path.Combine(dir, "other.txt"));
Thread.Sleep(200);

watcher.Dispose();
Directory.Delete(dir, true);

We watch only for size changes, change the timestamp of a file, append to it, and create and delete another file.

NotifyFilter = NotifyFilters.Size,

Without FileName, the Created and Deleted events are not raised.

On Windows, changing only the timestamp does not change the size, so no event is raised. On Linux, inotify has fewer kinds of notifications than Windows, so the flags are mapped coarsely: a change of the timestamp and the creation of an empty file both raise a Changed event, as the output shows. Code that needs exact information should check the file itself in the event handler.

$ dotnet run
touch
Changed: data.txt
append
Changed: data.txt
create and delete another file
Changed: other.txt

Watching subdirectories

The IncludeSubdirectories property extends the watcher to the whole directory tree.

Program.cs
string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

using var watcher = new FileSystemWatcher(dir, "*.txt")
{
    IncludeSubdirectories = true,
    NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName,
};

watcher.Created += (s, e) => Console.WriteLine($"{e.ChangeType}: {e.Name}");
watcher.EnableRaisingEvents = true;

Directory.CreateDirectory(Path.Combine(dir, "2026", "03"));
Thread.Sleep(200);

File.WriteAllText(Path.Combine(dir, "top.txt"), "");
File.WriteAllText(Path.Combine(dir, "2026", "03", "report.txt"), "");
File.WriteAllText(Path.Combine(dir, "2026", "03", "report.pdf"), "");
Thread.Sleep(200);

watcher.Dispose();
Directory.Delete(dir, true);

We create a nested directory and files in the root and in the nested directory.

using var watcher = new FileSystemWatcher(dir, "*.txt")

The second constructor argument sets the filter. The created directories do not match it, so they are not reported.

IncludeSubdirectories = true,

With subdirectories included, Name holds the path relative to the watched directory. On Linux, the watcher adds an inotify watch for each subdirectory, so very large trees may reach the system limit set in /proc/sys/fs/inotify/max_user_watches.

$ dotnet run
Created: top.txt
Created: 2026/03/report.txt

Waiting for a change

The WaitForChanged method blocks until a change happens or a timeout expires. It does not need event handlers.

Program.cs
string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

using var watcher = new FileSystemWatcher(dir, "*.done");

_ = Task.Run(async () =>
{
    await Task.Delay(300);
    File.WriteAllText(Path.Combine(dir, "job1.done"), "");
});

WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Created, TimeSpan.FromSeconds(5));
Console.WriteLine($"TimedOut: {result.TimedOut}, Name: {result.Name}");

result = watcher.WaitForChanged(WatcherChangeTypes.Created, TimeSpan.FromMilliseconds(500));
Console.WriteLine($"TimedOut: {result.TimedOut}, Name: {result.Name ?? "-"}");

Directory.Delete(dir, true);

A background task creates a file after 300 milliseconds. We wait for it, and then wait again for a file that never appears.

WaitForChangedResult result = watcher.WaitForChanged(WatcherChangeTypes.Created, TimeSpan.FromSeconds(5));

The method returns a WaitForChangedResult with the type of change and the file name. The overload with a TimeSpan was added in .NET 7; older code passes the timeout in milliseconds.

Console.WriteLine($"TimedOut: {result.TimedOut}, Name: {result.Name ?? "-"}");

When the timeout expires, TimedOut is true and the name is null.

$ dotnet run
TimedOut: False, Name: job1.done
TimedOut: True, Name: -

Debouncing events

Editors and other programs often write a file in several steps, which raises a burst of events. Reacting to each one wastes work and may read a file that is only half written. Debouncing waits until the events stop for a while and then reacts once.

Program.cs
using System.Collections.Concurrent;

string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

var pending = new ConcurrentDictionary<string, CancellationTokenSource>();
int raw = 0;

using var watcher = new FileSystemWatcher(dir)
{
    NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.Size | NotifyFilters.FileName,
};

watcher.Changed += OnChange;
watcher.Created += OnChange;
watcher.EnableRaisingEvents = true;

string file = Path.Combine(dir, "settings.json");

for (int i = 1; i <= 5; i++)
{
    File.WriteAllText(file, $"{{\"version\": {i}}}");
    Thread.Sleep(30);
}

Thread.Sleep(800);
Console.WriteLine($"raw events: {raw}");

watcher.Dispose();
Directory.Delete(dir, true);

void OnChange(object sender, FileSystemEventArgs e)
{
    Interlocked.Increment(ref raw);

    var cts = new CancellationTokenSource();
    pending.AddOrUpdate(e.FullPath, cts, (_, old) => { old.Cancel(); return cts; });

    Task.Delay(300, cts.Token).ContinueWith(t =>
    {
        if (t.IsCanceled) return;

        pending.TryRemove(new KeyValuePair<string, CancellationTokenSource>(e.FullPath, cts));
        Console.WriteLine($"reload {e.Name}: {File.ReadAllText(e.FullPath)}");
    });
}

We write a settings file five times in quick succession and reload it only once.

pending.AddOrUpdate(e.FullPath, cts, (_, old) => { old.Cancel(); return cts; });

For each event, we start a new delay for the file and cancel the previous one. The ConcurrentDictionary is needed because the events arrive on different threads.

Task.Delay(300, cts.Token).ContinueWith(t =>

Only the delay that is not canceled, the one after the last event, reloads the file. The program received several raw events, but it reads the file once, with its final content.

$ dotnet run
reload settings.json: {"version": 5}
raw events: 7

Errors

The watched directory must exist, and the watcher can lose events when they come too fast.

Program.cs
try
{
    using var watcher = new FileSystemWatcher(Path.Combine("demo", "missing"));
}
catch (ArgumentException e)
{
    Console.WriteLine($"{e.GetType().Name}: {e.Message.Replace(Environment.CurrentDirectory, ".")}");
}

string dir = Path.GetFullPath("demo");
Directory.CreateDirectory(dir);

using (var watcher = new FileSystemWatcher(dir))
{
    Console.WriteLine($"InternalBufferSize: {watcher.InternalBufferSize}");

    watcher.Error += (s, e) =>
    {
        Exception ex = e.GetException();
        Console.WriteLine($"Error: {ex.GetType().Name}");
    };

    watcher.EnableRaisingEvents = true;
}

Directory.Delete(dir, true);

We create a watcher for a missing directory and subscribe to the Error event of a working watcher.

using var watcher = new FileSystemWatcher(Path.Combine("demo", "missing"));

The constructor throws an ArgumentException, not a DirectoryNotFoundException.

Console.WriteLine($"InternalBufferSize: {watcher.InternalBufferSize}");

On Windows, notifications are stored in a buffer of 8 KB by default. When many changes happen at once, the buffer overflows and the Error event receives an InternalBufferOverflowException. The buffer can be raised to 64 KB. On Linux, the size of the inotify queue is set by the system.

watcher.Error += (s, e) =>

After an overflow, events are lost, so a program that must not miss any file should rescan the directory in the error handler. The event is also raised when the watched directory becomes unavailable, for example when a network share disconnects.

$ dotnet run
ArgumentException: The directory name 'demo/missing' does not exist. (Parameter 'path')
InternalBufferSize: 8192

Source

FileSystemWatcher class

In this article we have monitored file system changes with the FileSystemWatcher class in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.