Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Trap Events From File
Welcome to our comprehensive guide on creating a C# program to trap events from a file. File event monitoring allows your application to respond to file system changes in real-time, making it useful for scenarios like log monitoring, file synchronization, and automated backup systems.
Understanding FileSystemWatcher
In C#, the FileSystemWatcher class monitors file system events and triggers notifications when files or directories are created, modified, deleted, or renamed. This class provides a powerful mechanism for building responsive applications that react to file system changes.
FileSystemWatcher offers several key events
Created Occurs when a file or directory is created in the specified path.
Changed Occurs when a file or directory in the specified path is changed.
Deleted Occurs when a file or directory is deleted from the specified path.
Renamed Occurs when a file or directory in the specified path is renamed.
Syntax
Following is the basic syntax for creating and configuring a FileSystemWatcher
FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\YourPath"; watcher.Filter = "*.*"; // Watch all files watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName; // Register event handlers watcher.Created += OnCreated; watcher.Changed += OnChanged; watcher.Deleted += OnDeleted; watcher.Renamed += OnRenamed; // Enable event raising watcher.EnableRaisingEvents = true;
Basic File Event Monitoring
The following example demonstrates how to create a basic file monitoring program using FileSystemWatcher
using System;
using System.IO;
class Program {
static void Main() {
// Create a temporary directory for demonstration
string watchPath = Path.Combine(Path.GetTempPath(), "FileWatchDemo");
Directory.CreateDirectory(watchPath);
Console.WriteLine($"Monitoring directory: {watchPath}");
// Create FileSystemWatcher
FileSystemWatcher watcher = new FileSystemWatcher(watchPath);
// Set filter to watch all files
watcher.Filter = "*.*";
// Register event handlers using lambda expressions
watcher.Created += (sender, e) => Console.WriteLine($"Created: {e.Name}");
watcher.Changed += (sender, e) => Console.WriteLine($"Changed: {e.Name}");
watcher.Deleted += (sender, e) => Console.WriteLine($"Deleted: {e.Name}");
watcher.Renamed += (sender, e) => Console.WriteLine($"Renamed: {e.OldName} to {e.Name}");
// Enable event raising
watcher.EnableRaisingEvents = true;
// Create some test files to demonstrate events
Console.WriteLine("\nCreating test files...<br>");
string testFile1 = Path.Combine(watchPath, "test1.txt");
string testFile2 = Path.Combine(watchPath, "test2.txt");
File.WriteAllText(testFile1, "Initial content");
System.Threading.Thread.Sleep(100); // Brief pause for events
File.AppendAllText(testFile1, "\nAppended content");
System.Threading.Thread.Sleep(100);
File.Move(testFile1, testFile2);
System.Threading.Thread.Sleep(100);
File.Delete(testFile2);
System.Threading.Thread.Sleep(100);
// Cleanup
watcher.Dispose();
Directory.Delete(watchPath, true);
Console.WriteLine("\nFile monitoring demonstration completed.");
}
}
The output of the above code is
Monitoring directory: C:\Users\[User]\AppData\Local\Temp\FileWatchDemo Creating test files... Created: test1.txt Changed: test1.txt Renamed: test1.txt to test2.txt Deleted: test2.txt File monitoring demonstration completed.
Advanced FileSystemWatcher Configuration
FileSystemWatcher provides several properties for fine-tuning monitoring behavior
using System;
using System.IO;
class AdvancedFileWatcher {
static void Main() {
string watchPath = Path.Combine(Path.GetTempPath(), "AdvancedDemo");
Directory.CreateDirectory(watchPath);
FileSystemWatcher watcher = new FileSystemWatcher(watchPath);
// Monitor only .txt files
watcher.Filter = "*.txt";
// Monitor specific types of changes
watcher.NotifyFilter = NotifyFilters.FileName |
NotifyFilters.LastWrite |
NotifyFilters.Size;
// Include subdirectories
watcher.IncludeSubdirectories = true;
// Set buffer size (default is 8KB)
watcher.InternalBufferSize = 32768; // 32KB
// Register detailed event handlers
watcher.Created += OnFileCreated;
watcher.Changed += OnFileChanged;
watcher.Deleted += OnFileDeleted;
watcher.Error += OnWatcherError;
watcher.EnableRaisingEvents = true;
Console.WriteLine("Advanced file watcher started. Monitoring .txt files only.");
// Create test scenarios
string subDir = Path.Combine(watchPath, "SubFolder");
Directory.CreateDirectory(subDir);
File.WriteAllText(Path.Combine(watchPath, "root.txt"), "Root file");
File.WriteAllText(Path.Combine(subDir, "sub.txt"), "Sub file");
File.WriteAllText(Path.Combine(watchPath, "ignore.log"), "Should be ignored");
System.Threading.Thread.Sleep(500);
// Cleanup
watcher.Dispose();
Directory.Delete(watchPath, true);
Console.WriteLine("Advanced monitoring completed.");
}
static void OnFileCreated(object sender, FileSystemEventArgs e) {
Console.WriteLine($"[CREATE] {e.FullPath} at {DateTime.Now:HH:mm:ss}");
}
static void OnFileChanged(object sender, FileSystemEventArgs e) {
Console.WriteLine($"[CHANGE] {e.FullPath} at {DateTime.Now:HH:mm:ss}");
}
static void OnFileDeleted(object sender, FileSystemEventArgs e) {
Console.WriteLine($"[DELETE] {e.FullPath} at {DateTime.Now:HH:mm:ss}");
}
static void OnWatcherError(object sender, ErrorEventArgs e) {
Console.WriteLine($"[ERROR] Watcher error: {e.GetException().Message}");
}
}
The output of the above code is
Advanced file watcher started. Monitoring .txt files only. [CREATE] C:\Users\[User]\AppData\Local\Temp\AdvancedDemo\root.txt at 14:23:15 [CHANGE] C:\Users\[User]\AppData\Local\Temp\AdvancedDemo\root.txt at 14:23:15 [CREATE] C:\Users\[User]\AppData\Local\Temp\AdvancedDemo\SubFolder\sub.txt at 14:23:15 [CHANGE] C:\Users\[User]\AppData\Local\Temp\AdvancedDemo\SubFolder\sub.txt at 14:23:15 Advanced monitoring completed.
Key Properties and Configuration
| Property | Description | Default Value |
|---|---|---|
Path |
Directory to monitor | Empty string |
Filter |
File pattern to watch (e.g., "*.txt", "*.*") | "*.*" |
IncludeSubdirectories |
Whether to monitor subdirectories | false |
NotifyFilter |
Types of changes to monitor | LastWrite, FileName, DirectoryName |
EnableRaisingEvents |
Start/stop monitoring | false |
Common Use Cases
Log File Monitoring Watch application log files for new entries and trigger alerts or processing.
Configuration File Changes Automatically reload application settings when config files are modified.
File Synchronization Monitor directories for changes and sync them across systems.
Backup Systems Trigger backups when critical files are modified.
Development Tools Auto-compile or refresh when source files change.
Conclusion
The FileSystemWatcher class in C# provides a robust solution for monitoring file system events in real-time. By understanding its events, properties, and configuration options, you can build responsive applications that automatically react to file system changes, making it invaluable for scenarios like log monitoring, file synchronization, and automated processing systems.
