在C#中,你可以使用FileSystemWatcher
類來監控文件系統的變化。要設置監控條件,你需要在創建FileSystemWatcher
實例時配置相應的屬性。以下是一些常見的監控條件設置方法:
string path = @"C:\example_directory\";
FileSystemWatcher watcher = new FileSystemWatcher(path);
watcher.Filter = "*.txt"; // 監控所有.txt文件
watcher.Filter = "*example*.txt"; // 監控文件名包含"example"的所有.txt文件
watcher.NotifyFilter = NotifyFilters.CreationTime;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Deletion;
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.Renaming;
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
private static void OnChanged(object source, FileSystemEventArgs e)
{
// 處理文件更改事件
}
private static void OnRenamed(object source, RenamedEventArgs e)
{
// 處理文件重命名事件
}
通過組合這些屬性和事件處理程序,你可以根據需要設置監控條件。