FileSystemWatcher in C# – Monitor File Changes in Real-Time
👋 Introduction – Why FileSystemWatcher in C# Matters?
Imagine you’re working on an important project, and someone accidentally deletes or modifies a file in your system. Wouldn’t it be great if you could get notified instantly?
That’s where FileSystemWatcher in C# comes to the rescue! It helps you track file changes in real-time, whether files are created, modified, renamed, or deleted.
Think of it like a security camera watching over your files. Whenever something changes, it instantly notifies you! Sounds cool, right? Let’s dive in.
Sounds exciting? Let’s dive in! 😃
📚 What You Are Going to Learn in This Lesson
✔️ What is FileSystemWatcher in C#, and why is it useful?
✔️ How to use FileSystemWatcher to monitor file changes.
✔️ Real-world scenarios where this can be helpful.
✔️ Hands-on coding examples with complete code and output.
✔️ Useful tips and best practices.
🔍 What is FileSystemWatcher in C#?
FileSystemWatcher is a class in System.IO that allows you to monitor a directory (folder) and detect changes in files and subdirectories.
📌 What Can It Track?
✅ Created – Detect when a new file is added.
✅ Changed – Detect when an existing file is modified.
✅ Deleted – Detect when a file is removed.
✅ Renamed – Detect when a file is renamed.
💻 Basic Syntax of FileSystemWatcher in C#
Here’s how to create a FileSystemWatcher:
using System;
using System.IO;
class Program
{
static void Main()
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\MyFolder"; // Folder to monitor
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
watcher.EnableRaisingEvents = true; // Start monitoring
Console.WriteLine("Monitoring started... Press Enter to exit.");
Console.ReadLine();
}
private static void OnChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File {e.ChangeType}: {e.FullPath}");
}
private static void OnRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"File renamed from {e.OldFullPath} to {e.FullPath}");
}
}
📌 Explanation of the Code
- Set the folder path:
watcher.Path = @"C:\MyFolder";– This is the folder we are monitoring. - Choose what to monitor:
NotifyFilters.FileName | NotifyFilters.LastWritemeans we track file name changes and modifications. - Subscribe to events:
watcher.Changed→ Detects file modifications.watcher.Created→ Detects new file creation.watcher.Deleted→ Detects file deletion.watcher.Renamed→ Detects renaming of files.
- Enable monitoring:
watcher.EnableRaisingEvents = true;
Now, run the program and create, rename, edit, or delete a file in C:\MyFolder. You’ll see real-time updates in the console! 🖥️
Example: Logging File Changes to a Text File
Instead of printing to the console, let’s log changes into a text file.
using System;
using System.IO;
class FileLogger
{
static void Main()
{
string path = @"C:\MyFolder";
string logFile = @"C:\MyFolder\log.txt";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = path;
watcher.Filter = "*.*";
watcher.EnableRaisingEvents = true;
// Write logs to a file
watcher.Changed += (s, e) => File.AppendAllText(logFile, $"Modified: {e.FullPath} at {DateTime.Now}\n");
watcher.Created += (s, e) => File.AppendAllText(logFile, $"Created: {e.FullPath} at {DateTime.Now}\n");
watcher.Deleted += (s, e) => File.AppendAllText(logFile, $"Deleted: {e.FullPath} at {DateTime.Now}\n");
Console.WriteLine("Logging changes... Press any key to exit.");
Console.ReadKey();
}
}
🖥️ Output in log.txt
Created: C:\MyFolder\document.txt at 2025-02-28 14:30:21
Modified: C:\MyFolder\document.txt at 2025-02-28 14:32:10
Deleted: C:\MyFolder\document.txt at 2025-02-28 14:35:45
✅ Tip: This is useful for tracking who made changes in a team project folder.
🌍 Real-World Example – Why Do We Need FileSystemWatcher?
📁 Scenario: Auto Backup System
Imagine a company that automatically backs up important files whenever changes are detected. Instead of waiting for manual backups, a FileSystemWatcher can trigger an action instantly.
Let’s build a simple Auto Backup System!
using System;
using System.IO;
class AutoBackup
{
static void Main()
{
string sourceFolder = @"C:\Source";
string backupFolder = @"C:\Backup";
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = sourceFolder;
watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.LastWrite;
watcher.Created += (s, e) => File.Copy(e.FullPath, Path.Combine(backupFolder, Path.GetFileName(e.FullPath)), true);
watcher.EnableRaisingEvents = true;
Console.WriteLine("Auto Backup is running... Press Enter to exit.");
Console.ReadLine();
}
}
📝 Explanation:
- This monitors
C:\Sourcefor new files. - When a new file is added, it is automatically copied to
C:\Backup.
🔥 Try it yourself! Add a file to C:\Source, and it will instantly appear in C:\Backup! 🥳
🎯 More Use Cases for FileSystemWatcher in C#
✔️ Log File Monitoring – Keep track of changes in log files and analyze errors automatically.
✔️ Sync Folders – Detect changes in a folder and sync it to a cloud drive or another location.
✔️ Security Alerts – Detect unauthorized file access or tampering in sensitive directories.
⚠️ Common Pitfalls & Best Practices
🚨 Don’t monitor large directories – It can slow down performance.
🚨 Use filters wisely – Track only needed changes (NotifyFilters.FileName, LastWrite, etc.).
🚨 Always handle exceptions – Files can be locked or inaccessible.
🎉 Conclusion – You Are Now a File Monitoring Pro!
Congratulations! 🎊 Now you know how to use FileSystemWatcher in C# like a pro. You’ve seen how it works, built real-world examples, and learned best practices.
What’s next? 🤔 Let’s level up! 🚀
Next What?
In the next chapter, you will learn Handling Large Files and Memory Optimization in C#. If you deal with big files, memory issues can slow down your app. But don’t worry—we’ll fix that together! See you there! 😊
