我正在使用FileWatcher
来监控xml文件以跟踪更改。我只是想在文件内容改变,文件重命名甚至删除时触发一些方法。
订阅Changed
事件就足够了吗?
我是否还需要订阅其他活动?
答案 0 :(得分:2)
为了监控您想要的所有操作,您必须收听所有事件:创建,更改,删除,更新。
以下是样本:
public void init() {
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = "path/to/file";
watcher.NotifyFilter = NotifyFilters.LastAccess
| NotifyFilters.LastWrite | NotifyFilters.FileName
| NotifyFilters.DirectoryName;
// Only watch text files.
watcher.Filter = "*.txt";
// Add event handlers.
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.Deleted += new FileSystemEventHandler(OnChanged);
watcher.Renamed += new RenamedEventHandler(OnRenamed);
// Begin watching.
watcher.EnableRaisingEvents = true;
}
// Define the event handlers.
private static void OnChanged(object source, FileSystemEventArgs e) {
// Specify what is done when a file is changed, created, or deleted.
}
private static void OnRenamed(object source, RenamedEventArgs e) {
// Specify what is done when a file is renamed.
}