Pau*_*aul 15 c# filesystemwatcher
我正在编写ac#program,以便在添加或删除文件时通知我.我在我的Windows 7机器上运行它并在我们的网络上观看FTP服务器.
它工作正常但会突然停止捕捉任何事件.我猜它可能正在失去与服务器的连接,或者网络中存在故障.
如何在代码中处理这种情况.是否有一些我可以观察的异常并尝试重新启动FileSystemWatcher对象.
任何建议和代码示例将不胜感激.
Pau*_*aul 17
我需要为FileSystemWatcher添加一个错误处理程序
fileSystemWatcher.Error += new ErrorEventHandler(OnError);
Run Code Online (Sandbox Code Playgroud)
然后添加以下代码:
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 + "\r\n";
}
else
{
txtResults.Text += "Error: Watched directory not accessible at " + DateTime.Now + "\r\n";
}
NotAccessibleError(fileSystemWatcher ,e);
}
Run Code Online (Sandbox Code Playgroud)
以下是我重置SystemFileWatcher对象的方法:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
我认为这段代码应该按照我的意愿去做.
小智 9
之前的答案并没有完全解决它,我不得不重置观察者而不是打开和关闭它.我在窗口服务上使用filesystemwatcher
void NotAccessibleError(FileSystemWatcher source, ErrorEventArgs e)
{
int iMaxAttempts = 120;
int iTimeOut = 30000;
int i = 0;
while ((!Directory.Exists(source.Path) || source.EnableRaisingEvents == false) && i < iMaxAttempts)
{
i += 1;
try
{
source.EnableRaisingEvents = false;
if (!Directory.Exists(source.Path))
{
MyEventLog.WriteEntry("Directory Inaccessible " + source.Path + " at " + DateTime.Now.ToString("HH:mm:ss"));
System.Threading.Thread.Sleep(iTimeOut);
}
else
{
// ReInitialize the Component
source.Dispose();
source = null;
source = new System.IO.FileSystemWatcher();
((System.ComponentModel.ISupportInitialize)(source)).BeginInit();
source.EnableRaisingEvents = true;
source.Filter = "*.tif";
source.Path = @"\\server\dir";
source.NotifyFilter = System.IO.NotifyFilters.FileName;
source.Created += new System.IO.FileSystemEventHandler(fswCatchImages_Changed);
source.Renamed += new System.IO.RenamedEventHandler(fswCatchImages_Renamed);
source.Error += new ErrorEventHandler(OnError);
((System.ComponentModel.ISupportInitialize)(source)).EndInit();
MyEventLog.WriteEntry("Try to Restart RaisingEvents Watcher at " + DateTime.Now.ToString("HH:mm:ss"));
}
}
catch (Exception error)
{
MyEventLog.WriteEntry("Error trying Restart Service " + error.StackTrace + " at " + DateTime.Now.ToString("HH:mm:ss"));
source.EnableRaisingEvents = false;
System.Threading.Thread.Sleep(iTimeOut);
}
}
}
Run Code Online (Sandbox Code Playgroud)