How can the FileSystemWatcher be used in C#?
The FileSystemWatcher class is used to monitor changes in the file system, such as creating, modifying, deleting, and renaming files or directories. Below are the basic steps of using the FileSystemWatcher class:
- Create a FileSystemWatcher object and specify the path to monitor.
- Specify the type of files to monitor or choose to monitor all files.
- Choose the types of changes to monitor (create, modify, delete, rename).
- Option: Specify if subdirectories should be monitored (optional).
- Register an event handler to handle file system change events.
- Start monitoring.
Here is an example demonstrating how to use the FileSystemWatcher class to monitor file changes in a specified path.
using System;
using System.IO;
class Program
{
static void Main()
{
// 创建FileSystemWatcher对象并设置要监视的路径
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "C:\\Path\\To\\Directory";
// 设置要监视的文件类型或所有文件
watcher.Filter = "*.txt";
// 设置要监视的更改类型
watcher.NotifyFilter = NotifyFilters.LastWrite;
// 设置是否监视子目录
watcher.IncludeSubdirectories = true;
// 注册事件处理程序
watcher.Changed += OnChanged;
// 启动监视
watcher.EnableRaisingEvents = true;
// 等待用户输入以退出程序
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
}
// 文件更改事件处理程序
private static void OnChanged(object source, FileSystemEventArgs e)
{
// 处理文件更改事件
Console.WriteLine($"File {e.Name} has been {e.ChangeType}.");
}
}
In the example above, we created a FileSystemWatcher object to monitor changes to .txt files in the path “C:\Path\To\Directory”. Then, we registered an OnChanged event handler to handle file change events. Finally, we started the monitoring process and printed information about file changes on the console. You can customize the path, file type, and event handler to meet your needs.