To watch for file changes (like creation, deletion, or modification) in real-time in C#, you can use the built-in
FileSystemWatcher class in the System.IO namespace.
Example: Monitor a directory for changes
using System;
using System.IO;
class Program
{
static void Main()
{
string pathToWatch = @"C:\MyFolder";
using (FileSystemWatcher watcher = new FileSystemWatcher(pathToWatch))
{
// Watch for changes in LastWrite times, and creation/deletion of files
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite | NotifyFilters.CreationTime;
// Only watch text files
watcher.Filter = "*.txt";
// Event handlers
watcher.Created += OnCreated;
watcher.Deleted += OnDeleted;
watcher.Changed += OnChanged;
watcher.Renamed += OnRenamed;
// Begin watching
watcher.EnableRaisingEvents = true;
Console.WriteLine("Watching for changes. Press Enter to exit...");
Console.ReadLine(); // Keep the program running
}
}
private static void OnCreated(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File created: {e.FullPath}");
private static void OnDeleted(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File deleted: {e.FullPath}");
private static void OnChanged(object sender, FileSystemEventArgs e) =>
Console.WriteLine($"File changed: {e.FullPath}");
private static void OnRenamed(object sender, RenamedEventArgs e) =>
Console.WriteLine($"File renamed: {e.OldFullPath} -> {e.FullPath}");
}
Notes:
FileSystemWatcher supports events: Created, Deleted,
Changed, and Renamed.
Use IncludeSubdirectories = true to monitor subfolders.
It's best suited for local directories (not reliable over network shares).
Markdown for AI
A clean, structured version of this page for AI assistants and LLMs.
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy.
To watch for file changes (like creation, deletion, or modification) in real-time in C#, you can use the built-in
FileSystemWatcherclass in theSystem.IOnamespace.Example: Monitor a directory for changes
Notes:
FileSystemWatchersupports events:Created,Deleted,Changed, andRenamed.IncludeSubdirectories = trueto monitor subfolders.