C# FileSystemWatcher: Monitoring File System Changes in Real-Time
What is FileSystemWatcher?
The FileSystemWatcher
class is a built-in component in C# that lets you keep an eye on a specific directory or file for changes. It can notify your application when:
- A new file is created.
- An existing file is modified.
- A file is deleted.
- A file is renamed.
This makes it an invaluable tool for applications that need to respond to file system events in real-time.
Setting Up FileSystemWatcher
To get started, you’ll need to create an instance of the FileSystemWatcher
class and configure its properties. Here’s a step-by-step guide:
1. Create a FileSystemWatcher Instance
First, create an instance of the FileSystemWatcher
class:
using System.IO;
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
2. Specify the Directory to Monitor
Use the Path
property to specify the directory you want to monitor. For example, to monitor a folder called C:\MyFolder
, you would write:
fileSystemWatcher.Path = @"C:\MyFolder";
3. Filter Files (Optional)
If you only want to monitor specific types of files, you can use the Filter
property. For instance, to watch only .txt
files, set the filter like this:
fileSystemWatcher.Filter = "*.txt";
If you want to monitor all files, you can omit this property or set it to *.*
.
Subscribing to Events
The FileSystemWatcher
class provides several events that you can subscribe to:
- Created: Triggered when a new file is created.
- Changed: Triggered when a file is modified.
- Deleted: Triggered when a file is deleted.
- Renamed: Triggered when a file is renamed.
Here’s how you can subscribe to these events:
fileSystemWatcher.Created += OnFileCreated;
fileSystemWatcher.Changed += OnFileChanged;
fileSystemWatcher.Deleted += OnFileDeleted;
fileSystemWatcher.Renamed += OnFileRenamed;
Implementing Event Handlers
Next, you’ll need to define the event handlers that will be called when these events occur. Here’s an example of how to implement them:
private static void OnFileCreated(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File created: {e.Name} - {e.FullPath}");
}
private static void OnFileChanged(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File changed: {e.Name} - {e.FullPath}");
}
private static void OnFileDeleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine($"File deleted: {e.Name} - {e.FullPath}");
}
private static void OnFileRenamed(object sender, RenamedEventArgs e)
{
Console.WriteLine($"File renamed: {e.OldName} -> {e.Name} - {e.FullPath}");
}
In these handlers:
e.Name
gives you the name of the file.
e.FullPath
provides the full path of the file.
- For renamed files,
e.OldName
gives the previous name of the file.
Starting and Stopping the FileSystemWatcher
Once you’ve set up the FileSystemWatcher
and subscribed to the events, you need to start monitoring. This is done by setting the EnableRaisingEvents
property to true
:
fileSystemWatcher.EnableRaisingEvents = true; // Start monitoring
To stop monitoring, simply set EnableRaisingEvents
false:
fileSystemWatcher.EnableRaisingEvents = false; // Stop monitoring
Handling Exceptions
File system operations can sometimes fail, and the FileSystemWatcher
can throw exceptions if something goes wrong. To ensure your application remains stable, wrap your code in a try-catch
block:
try
{
fileSystemWatcher.EnableRaisingEvents = true;
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred: {ex.Message}");
}
Important Considerations
-
Multiple Events for a Single Change
The FileSystemWatcher
may raise multiple events for a single file system change. For example, saving a file might trigger both a Changed
and a Created
event. To handle this, you may need to implement additional logic, such as debouncing or filtering duplicate events.
-
Performance Impact
Monitoring large directories or frequently changing files can impact performance. Use filters and optimize your event handlers to minimize overhead.
-
Network Drives
The FileSystemWatcher
can monitor network drives, but it may not work as reliably as local directories due to network latency and permissions.
Practical Example: Monitoring a Log Folder
Let’s say you want to monitor a folder where log files are stored. Whenever a new log file is added, you want to process it immediately. Here’s how you can do it:
FileSystemWatcher logWatcher = new FileSystemWatcher
{
Path = @"C:\Logs",
Filter = "*.log",
EnableRaisingEvents = true
};
logWatcher.Created += (sender, e) =>
{
Console.WriteLine($"New log file detected: {e.Name}");
// Add your log processing logic here
};
Conclusion
The FileSystemWatcher
class in C# is a powerful tool for building applications that need to respond to file system changes in real-time. Whether you’re building a file synchronization tool, a log monitoring system, or an automated data processing application, the FileSystemWatcher
can save you a lot of effort.
By following the steps and examples in this article, you can easily set up and use the FileSystemWatcher
in your own projects. Just remember to handle exceptions and account for potential quirks like multiple events for a single change.
Happy coding, and may your file system monitoring be smooth and efficient!