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可能會觸發多次事件,因此需要適當處理重復事件的情況。此外,需要注意文件系統操作可能引起的性能問題和并發問題。