C# › File I/O & Streams

How do you use FileSystemWatcher to monitor a directory for file changes, and what are its common reliability pitfalls?

Advanced

Answer

FileSystemWatcher raises events (Created, Changed, Deleted, Renamed) when files change within a monitored directory — a common pitfall is that a single logical file save can trigger MULTIPLE rapid Changed events (due to how some applications write files), so production code typically needs debouncing logic to avoid processing the same change multiple times.
var watcher = new FileSystemWatcher(@"C:\Data") { EnableRaisingEvents = true };
watcher.Changed += (sender, e) => {
  Console.WriteLine($"File changed: {e.FullPath}");
  // In production: debounce here, since this can fire multiple times per actual save
};
Real-world example Building a 'hot reload' feature that automatically reprocesses a configuration file whenever it's edited on disk.

Common follow-ups: What's the recommended approach for debouncing FileSystemWatcher's often-duplicate Changed events?