问题
I have a windows application which uses FileSystemWatcher to monitor the change of files. Multiple file locations can be added and for each location a new instance of FileSystemWatcher is created and the location is added to a listbox. There is an option to delete a location from the listbox. I need to delete/dispose the particular instance of FileSystemWatcher when a location is deleted. Is there any way to attain this? Thanks in advance.
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;
}
}
回答1:
Well you'll need to keep a reference to the instance, e.g. as the value in the list box entry, or perhaps a Dictionary<string, FileSystemWatcher>
to map from path to watcher. Then just dispose of the watcher and remove it from the dictionary / remove the list item.
来源:https://stackoverflow.com/questions/12119863/how-to-delete-a-particular-instance-of-filesystemwatcher-object