Home >Backend Development >C++ >How Can I Monitor File Changes in C#?
Monitor file changes in C#
Problem: Looking for a mechanism to detect file modifications on disk.
Answer: The FileSystemWatcher
class provides a reliable solution.
Instructions:
FileSystemWatcher
Class monitors file changes in the specified directory. When a change occurs, it raises an event that can be processed to perform the desired action. The following code demonstrates how to use FileSystemWatcher
:
<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 += new FileSystemEventHandler(OnChanged); watcher.Created += new FileSystemEventHandler(OnChanged); watcher.Deleted += new FileSystemEventHandler(OnChanged); watcher.Renamed += new RenamedEventHandler(OnRenamed); // 开始监控 watcher.EnableRaisingEvents = true; } private static void OnChanged(object source, FileSystemEventArgs e) { // 定义在更改、创建或删除文件时要执行的操作 Console.WriteLine("文件: " + e.FullPath + " " + e.ChangeType); } private static void OnRenamed(object source, RenamedEventArgs e) { // 定义在文件重命名时要执行的操作 Console.WriteLine("文件: {0} 重命名为 {1}", e.OldFullPath, e.FullPath); }</code>
In this example, the monitor is configured to monitor changes to text files (*.txt) in a specific path. When a file within that path is changed, created, deleted, or renamed, the corresponding event handler is called, allowing you to take action accordingly, such as logging the event or updating the state of your application.
The above is the detailed content of How Can I Monitor File Changes in C#?. For more information, please follow other related articles on the PHP Chinese website!