如何删除FileSystemWatcher对象的特定实例

Tec*_*hDo 1 c# filesystemwatcher windows-applications

我有一个Windows应用程序,它使用FileSystemWatcher来监视文件的更改.可以添加多个文件位置,并为每个位置创建一个新的FileSystemWatcher实例,并将该位置添加到列表框中.可以选择从列表框中删除位置.删除位置时,我需要删除/处理FileSystemWatcher的特定实例.有没有办法达到这个目的?提前致谢.

FileSystemWatcher fsw;

    private void CreateFWInstance(string strLoc)
    {
        if (strLoc != string.Empty)
        {
            fsw = new FileSystemWatcher();
            fsw.Changed += new FileSystemEventHandler(OnChanged);

            fsw.Path = strLoc;
            fsw.SynchronizingObject = this;

            fsw.EnableRaisingEvents = true;

        }
    }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 6

那么你需要保持对实例的引用,例如作为列表框条目中的,或者可能是Dictionary<string, FileSystemWatcher>从路径到观察者的映射.然后只需处理观察者并将其从字典中删除/删除列表项.