新蜂警报。问题:我填充了一个组合框,用户进行了选择。然后我创建并启用 FSW。一切正常,直到用户重新访问组合框以进行替代选择。此时,另一个 FSW 被实例化,导致基于“文件正在使用”错误的 IO 异常。当用户在组合框中进行后续选择时,我需要关闭 FSW(或销毁实例化)。整个程序由带有组合框的 Winform 驱动。
当用户重新访问组合框并进行另一个选择时,如何打开/关闭 FSW,或破坏 FSW 实例并允许创建一个新的、类似的?
调用 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();
}
}
WatchIt() 的代码。我打算使用 bool bCreateWatcher 来打开和关闭 FSW。
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");
}
}