Monitor file changes using C#’s FileSystemWatcher
In a C# application, you may need to detect file modifications on disk. This can be easily achieved through the FileSystemWatcher class provided by the .NET Framework.
Use FileSystemWatcher to implement file change detection
<code class="language-csharp">private static void OnChanged(object source, FileSystemEventArgs e) { // 当文件更改、创建或删除时,实现所需的动作。 Console.WriteLine($"文件: {e.FullPath} {e.ChangeType}"); } private static void OnRenamed(object source, RenamedEventArgs e) { // 定义在文件重命名时要执行的动作。 Console.WriteLine($"文件: {e.OldFullPath} 重命名为 {e.FullPath}"); }</code>
Sample code:
The following code snippet demonstrates how to use FileSystemWatcher to monitor text files in a specific directory:
<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 += OnChanged; watcher.Deleted += OnChanged; watcher.Renamed += OnRenamed; // 开始监控。 watcher.EnableRaisingEvents = true; }</code>
By implementing this mechanism, C# applications can effectively track and respond to file modifications on disk, enabling real-time data synchronization, version control, and other critical operations.
The above is the detailed content of How Can I Monitor File Changes in C# Using FileSystemWatcher?. For more information, please follow other related articles on the PHP Chinese website!