FileSystemWatcher是一个.NET类,允许开发人员监视文件系统的更改并作出相应的响应。以下是一些常见的用法示例:
- 监视文件夹中的文件更改:
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = @"C:\Users\JohnDoe\Documents";
watcher.Filter = "*.txt";
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.Changed += OnChanged;
watcher.Created += OnChanged;
watcher.Deleted += OnChanged;
watcher.Renamed += OnRenamed;
watcher.EnableRaisingEvents = true;
private static void OnChanged(object source, FileSystemEventArgs e)
{
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
Console.WriteLine("File: {0} renamed to {1}", e.OldFullPath, e.FullPath);
}
- 监视整个文件系统的更改:
FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\"; watcher.IncludeSubdirectories = true; watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName; watcher.Changed += OnChanged; watcher.Created += OnChanged; watcher.Deleted += OnChanged; watcher.Renamed += OnRenamed; watcher.EnableRaisingEvents = true;
- 只监视特定文件的更改:
FileSystemWatcher watcher = new FileSystemWatcher(); watcher.Path = @"C:\Users\JohnDoe\Documents"; watcher.Filter = "importantFile.txt"; watcher.NotifyFilter = NotifyFilters.LastWrite; watcher.Changed += OnChanged; watcher.EnableRaisingEvents = true;
- 停止监视器:
watcher.EnableRaisingEvents = false; watcher.Dispose();
需要注意的是,FileSystemWatcher可能会触发多次事件,因此需要适当处理重复事件的情况。此外,需要注意文件系统操作可能引起的性能问题和并发问题。