Newbee alert. Problem: I populate a combo box, user makes a selection. I then create and enable a FSW. All works well, until user revisits combo box to make an alternate selection. At that point, another FSW is instantiated resulting in IO Exceptions based on ‘file in use’ errors. I need to switch off the FSW (or destroy the instantiation) when the user makes a subsequent selection in the combo box. Entire program is driven from a Winform with the combo box.
How do either toggle the FSW on/off, or destroy the FSW instantiation and allow a new, similar one to be created when the user revisits the combo box and makes another selection?
Code that calls for instantiation of the FSW:
private void MinAndGo()
{
if (strLblPtr != null)
{
if(strLblPtr != "None")
{
if (!CheckMyPrinter(strLblPtr))
{
MessageBox.Show(ForegroundWindow.Instance, "Printer is not ready. Make sure it's turned on "
+ "and has paper loaded.", "Printer Not Ready");
}
}
this.WindowState = FormWindowState.Minimized;
this.Activate();
bCreateWatcher = true;
Watchit();
}
}
Code for WatchIt(). I was intending on using the bool bCreateWatcher to toggle the FSW on and off.
private static void Watchit()
{
List<string> list = new List<string>();
list.Add("C:\\SAMMS\\pcl");
list.Add("C:\\SAMMS\\lbl");
foreach (string my_path in list)
{
Watch(my_path);
}
}
private static void Watch(string watch_folder)
{
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.InternalBufferSize = 8192; //defaults to 4KB, need 8KB buffer
watcher.Path = watch_folder;
watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
| NotifyFilters.FileName | NotifyFilters.DirectoryName;
watcher.Filter = "*.*";
watcher.Created += new FileSystemEventHandler(OnCreated);
// Begin watching.
try
{
if (bCreateWatcher)
{
watcher.EnableRaisingEvents = true;
}
else
{
watcher.EnableRaisingEvents = false;
}
}
catch(Exception ex)
{
MessageBox.Show(ForegroundWindow.Instance, "FSW not set correctly" + ex, "FSW Error");
}
}
Ok, so it looks like you need to store your watcher somewhere, perhaps a dictionary keyed on the path? You’ll also need to have the class that this is all contained in implement
IDisposable, so that you can properly callDispose()on any watchers you currently have open with the class is disposed of. (You should then ensure that the containing class is also properly disposed.)I would refactor
Watch()to something like this (could probably be better):And your
Dispose()method: