Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท Files and I/O

The FileSystemWatcher class

Reference for FileSystemWatcher in C#: watch a directory for created, changed, deleted and renamed files, filters, buffer overflow and debouncing.

FileSystemWatcher (in System.IO) tells your program when files or folders in a directory change. You point it at a path, choose a filter and the kinds of changes you care about, set EnableRaisingEvents to true, and handle the Created, Changed, Deleted and Renamed events. Typical uses are reloading a configuration file, processing files dropped into an inbox folder, or rebuilding when sources change.

The events arrive on a thread-pool thread, not on your main thread, and the operating system may report one logical action as several events. A robust watcher therefore treats events as hints ("something happened to this path"), waits briefly, and then looks at the real state of the file.

C#
using var watcher = new FileSystemWatcher(folder, "*.txt");
watcher.Created += (_, e) => Console.WriteLine($"New: {e.Name}");
watcher.EnableRaisingEvents = true;

Try it

C# Waiting for a created file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Collecting several event types

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Syntax

C#
public FileSystemWatcher();
public FileSystemWatcher(string path);
public FileSystemWatcher(string path, string filter);

public bool EnableRaisingEvents { get; set; }
public string Path { get; set; }
public string Filter { get; set; }
public Collection<string> Filters { get; }
public NotifyFilters NotifyFilter { get; set; }
public bool IncludeSubdirectories { get; set; }
public int InternalBufferSize { get; set; }

public event FileSystemEventHandler Created, Changed, Deleted;
public event RenamedEventHandler Renamed;
public event ErrorEventHandler Error;
Name Description
Path The directory to watch. It must exist when EnableRaisingEvents becomes true.
Filter / Filters Name filter with * and ? wildcards (default *). Filters allows several patterns (.NET Core 3.0 and later).
NotifyFilter Which kinds of change raise Changed: file names, attributes, size, last write, security and so on.
IncludeSubdirectories Also watch everything below Path.
InternalBufferSize Size in bytes of the buffer the OS fills with change records (default 8 KB on Windows).
EnableRaisingEvents Starts or stops delivery of events.
Events FileSystemEventArgs has ChangeType, FullPath and Name; RenamedEventArgs adds OldFullPath and OldName.

Errors: ArgumentException when the path does not exist or the filter is invalid, PlatformNotSupportedException on platforms without a notification API.

Usage notes

  • Events can be duplicated. Saving a file in an editor often raises two or three Changed events (content, then attributes, sometimes a temp file renamed over the original). Collect paths in a set and process each once after a short quiet period, a technique called debouncing.
  • A file may still be in use. Created fires when the file appears, not when the writer finishes. Opening it right away can fail with an IOException; retry with a short delay, or have the producer write to a temp name and rename when done.
  • Handlers run on a thread-pool thread. Keep them short, catch exceptions inside (an unhandled exception ends the process), and hand slow work to a queue or Channel<T>.
  • Buffer overflow. If too many changes arrive before your handlers drain them, the Error event reports an InternalBufferOverflowException and some events are lost. Raise InternalBufferSize, narrow NotifyFilter and Filter, and keep handlers fast. After an overflow, rescan the directory instead of trusting events.
  • Dispose it. FileSystemWatcher is IDisposable and holds an OS handle; use using or call Dispose().
  • Platform differences. Windows uses ReadDirectoryChangesW, Linux uses inotify, macOS uses FSEvents or kqueue. Watching network shares is unreliable, and Linux limits the number of watches per user (fs.inotify.max_user_watches).
  • Not a transaction log. Changes made before EnableRaisingEvents = true are not reported. Scan the directory once after starting the watcher to close that gap.
  • Hot reload of configuration. For appsettings.json use reloadOnChange: true in the configuration builder, which uses a file watcher and handles most of these pitfalls.