0

我正在使用FileWatcher监视 xml 文件以跟踪更改。我只想在文件内容更改、文件重命名甚至删除时触发一些方法。

订阅Changed事件就够了?

我还需要订阅其他活动吗?

4

1 回答 1

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.     
}
于 2012-10-12T03:41:59.267 回答