2013-02-12 66 views
1

我在Windows服务中有一个FileSystemWatcher对象。我在使用该应用程序的控制台应用程序中将它编写为我的组件的存根。FileSystemWatcher OnError不适用于Windows服务

我的组件实例化FileSystemWatcher并设置为观察映射的驱动器。这对测试存根控制台应用程序和可部署Windows服务都非常适用。

我也onerror事件迷上了log4net的日志记录一个FATAL级别的错误:

public FileSystemWatcher CreateFileWatcher() 
    { 
     FileSystemWatcher watcher = new FileSystemWatcher(); 

     try 
     { 
      log.Info("Configuring DPIFileWatcher"); 
      watcher.Filter = "*.xml"; 
      log.Info("DPIFileWatcher Filter set to: *.xml"); 
      string watcherPath = ConfigurationManager.AppSettings["InoundPath"].ToString(); 
      watcher.Path = watcherPath; 
      log.Info(String.Format("DPIFileWatcher Path set to: {0}", watcherPath)); 

      watcher.Created += new FileSystemEventHandler(DPIWatcher_FileCreated); 
      watcher.Changed += new FileSystemEventHandler(DPIWatcher_FileChanged); 
      watcher.Error += new ErrorEventHandler(DPIWatcher_Error); 
      watcher.EnableRaisingEvents = true; 

      log.Info("DPIFileWatcher Configuration Successful."); 
     } 
     catch(Exception e) 
     { 
      log.Fatal(String.Format("Failed to configure DPIFileWatcher: {0}", e.Message)); 
     } 

     return watcher; 
    } 

这是我的错误事件:

private void DPIWatcher_Error(object source, ErrorEventArgs e) 
    { 
     log.Fatal(String.Format("FileWatacher error: {0}", e.GetException().Message)); 
    } 

如果我拔掉测试网络误差损失网卡,我从我的控制台应用程序得到以下日志错误:

FATAL [ 12] 2013-02-12 12:14:02,142 SMILLER-E6430 METHOD: DPIWatcher_Error  GenFileWatch.DPIFileWatcher- FileWatacher error: The specified network name is no longer available (C:\Development\GenFileWatch\GenFileWatch\DPIFileWatcher.cs: 447) 

但硫从Windows服务中运行时,s日志错误将不起作用。

有没有人有任何想法为什么或如何解决?

+0

它记录什么? – BNL 2013-02-12 18:07:59

+0

您是否从'OnStart'创建FileSystemWatcher实例?在创建它之后你对这个参考做了什么?它可能会过早收集,因此事件永远不会发生。只是一个猜测。 – 2013-02-12 18:57:54

回答

0

首先,您的服务是否可以通过可访问您要监控的目录的帐户运行。 99%的时间,运行“控制台”应用程序和运行“服务”在两个不同的用户环境下运行。如果该用户上下文无法访问该目录(或者URL只意味着另一个用户上下文中的某些内容),我不认为会调用OnError。

其次,FileSystemWatcher是相当不可靠的。它在大多数情况下都有效,但有时不会。它使用基本的原生函数``,这是记录与

When you first call ReadDirectoryChangesW, the system allocates a buffer to store change information. This buffer is associated with the directory handle until it is closed and its size does not change during its lifetime. Directory changes that occur between calls to this function are added to the buffer and then returned with the next call. If the buffer overflows, the entire contents of the buffer are discarded, the lpBytesReturned parameter contains zero, and the ReadDirectoryChangesW function fails with the error code ERROR_NOTIFY_ENUM_DIR

+0

感谢您的反馈。 尽管您的第一条评论,我们显然有权通过Windows服务访问文件共享,因为主要功能在服务中正常工作。文件服务器侦听映射驱动器上的文件夹中的新文件,并且创建的事件被触发,我们在那里做我们想做的事情。所以Win服务可以访问该驱动器。因此,我们无法弄清楚为什么onerror不会告诉我们“win服务中指定的网络名称不再可用”,就像它从控制台应用程序所做的那样。 – Sam 2013-02-13 13:43:30

+0

另外,在你的第二条评论中,我们刚开始测试这个,但是我读过你可以增加缓冲区大小来纠正这个问题。尽管对性能不利。所以试验和错误让它恰到好处。 – Sam 2013-02-13 13:45:26

相关问题