When developing various applications, we often need to monitor files or folders in the file system in real time so that we can react in a timely manner when the file content changes and files are created or deleted. In C#, classes provide us with such a powerful function.
1. Introduce the FileSystemWatcher class
First, introduce a namespace into the project, which is the prerequisite for using the FileSystemWatcher class:
using ;
2. Create and configure FileSystemWatcher instance
Here is a simple example showing how to create a FileSystemWatcher instance and set the directory, event type, and event handling functions it monitors:
public class FileFolderMonitor { private FileSystemWatcher _fileWatcher; public void StartMonitoring(string directoryPath) { // Create FileSystemWatcher instance _fileWatcher = new FileSystemWatcher(); // Set the directory path to monitor _fileWatcher.Path = directoryPath; // Set the type of change to monitor (for example: modify, create, delete) _fileWatcher.NotifyFilter = | | ; // Add event handler _fileWatcher.Changed += OnChanged; _fileWatcher.Created += OnChanged; _fileWatcher.Deleted += OnChanged; _fileWatcher.Renamed += OnRenamed; // Turn on event monitoring _fileWatcher.EnableRaisingEvents = true; ($"Start monitoring of folders: {directoryPath}"); } private void OnChanged(object source, FileSystemEventArgs e) { ($"File or folder changes: {},Event Type: {}"); } private void OnRenamed(object source, RenamedEventArgs e) { ($"Files or folders are renamed: Old path {} -> New path {}"); } public void StopMonitoring() { if (_fileWatcher != null) { // Stop raising events _fileWatcher.EnableRaisingEvents = false; // Clean up resources _fileWatcher.Dispose(); _fileWatcher = null; ("Stop monitoring folders"); } } }
3. Use and precautions
In the above code, we start monitoring of the specified directory by calling the StartMonitoring method and trigger the corresponding event handler when the file or subdirectory changes.
The NotifyFilter property is used to define the specific event type that needs to be listened to, such as the last write time, the change in the file name and directory name, etc.
Changeed, Created, Deleted, and Renamed events correspond to the content changes, new creation, deletes, and rename operations of files or folders, respectively.
Notes:
The FileSystemWatcher class does not guarantee the immediacy or sequentiality of events, especially in the case of large number of concurrent file operations, which may merge or delay triggering events.
When using FileSystemWatcher, you should ensure that resources are processed reasonably, especially when monitoring is no longer needed, the Dispose method should be called in time to release resources.
In summary, it is a powerful tool for real-time monitoring of file systems. With simple configuration and event processing, our applications can have the ability to respond sensitively to file system changes.
4. Extracurricular exploration, the file selection box pops up
public static string SelectFolder(string description = "Please select a folder:", rootFolder = ) { using (FolderBrowserDialog folderDialog = new FolderBrowserDialog()) { = description; = rootFolder; if (() == ) { return ; } } return ; }
5. Call example
Parameter call:
string selectedFolder = SelectFolder("Please select a save location:", );
Or use the default parameters and directly select "My Computer" as the root directory.
string myComputerSelectedFolder = SelectFolder();
Merge call methods to filter by empty filtering to avoid errors
string selectedFolderPath = SelectFolder(); if (!(selectedFolderPath)) { StartMonitoring(selectedFolderPath); }
This is the article about real-time monitoring folder changes in C#. For more related contents of C# monitoring folders, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!