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.LastWrite
means 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:\Source
for 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! π