I needed to add an error handler for the FileSystemWatcher
fileSystemWatcher.Error += new ErrorEventHandler(OnError);
And then add this code:
private void OnError(object source, ErrorEventArgs e)
{
if (e.GetException().GetType() == typeof(InternalBufferOverflowException))
{
txtResults.Text += "Error: File System Watcher internal buffer overflow at " + DateTime.Now + "
";
}
else
{
txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "
";
}
NotAccessibleError(fileSystemWatcher ,e);
}
Here is how I reset the SystemFileWatcher object:
static void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
source.EnableRaisingEvents = false;
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while (source.EnableRaisingEvents == false && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = true;
}
catch
{
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}
I think this code should do what I want it to do.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…