Complete C# Tutorial

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 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

  1. Set the folder path: watcher.Path = @"C:\MyFolder"; – This is the folder we are monitoring.
  2. Choose what to monitor: NotifyFilters.FileName | NotifyFilters.LastWrite means we track file name changes and modifications.
  3. 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.
  4. 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! 😊

Leave a Comment

Share this Doc

FileSystemWatcher – Realtime File Monitoring

Or copy link