Home >Backend Development >C++ >How Can I Monitor File System Changes in C#?
Use FileSystemWatcher to monitor file system changes in C#
In C#, use the FileSystemWatcher
class to conveniently receive notifications when files on disk are modified.
Implementation method:
TheFileSystemWatcher
class provides an event-based mechanism to monitor changes in the file system. To use this feature, create an instance of FileSystemWatcher
, specify the path to monitor, and configure the required notification filters.
Code example:
<code class="language-csharp">public void CreateFileWatcher(string path) { // 创建并配置 FileSystemWatcher FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = path; watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Filter = "*.txt"; // 为各种更改类型添加事件处理程序 watcher.Changed += OnChanged; watcher.Created += OnCreated; watcher.Deleted += OnDeleted; watcher.Renamed += OnRenamed; // 启动监视器 watcher.EnableRaisingEvents = true; }</code>
Event handler:
TheFileSystemWatcher
class provides specific event handlers for each type of file system change. These event handlers allow you to define actions to be performed when a file is changed, created, deleted, or renamed.
For example, OnChanged
an event handler can perform specific actions when a file is modified, such as logging the changes.
Event handling example:
<code class="language-csharp">private static void OnChanged(object source, FileSystemEventArgs e) { Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType); } private static void OnCreated(object source, FileSystemEventArgs e) { Console.WriteLine("File Created: " + e.FullPath); } private static void OnDeleted(object source, FileSystemEventArgs e) { Console.WriteLine("File Deleted: " + e.FullPath); } private static void OnRenamed(object source, RenamedEventArgs e) { Console.WriteLine("File Renamed: " + e.OldFullPath + " to " + e.FullPath); }</code>
By using the FileSystemWatcher
class you can effectively monitor changes in your file system and take appropriate actions based on detected changes.
The above is the detailed content of How Can I Monitor File System Changes in C#?. For more information, please follow other related articles on the PHP Chinese website!