3

背景信息:我正在使用服务中实现的 FileSystemWatcher 类来监视文件中的更改。这是触发 onCreate 事件时引发参数异常(路径不是合法形式)的编码部分。

FileMonitor.CS

public partial class FileMonitor:ServiceBase
{
 public FileSystemWatcher Watcher = new FileSystemWatcher();

    Private void FileWatcher()
    {
    FileActionHandler ActionHandler = new FileActionHandler();
    Watcher.Created += new FileSystemEventHandler(ActionHandler.onCreate);
    Watcher.Deleted += new FileSystemEventHandler(ActionHandler.onDelete);
    Watcher.Renamed += new RenamedEventHandler(ActionHandler.onRenamed);
    Watcher.EnableRaisingEvents = true;
    }
}

FileActionHandler.CS

 class FileActionHandler
 {
  FileMonitor FileMon = new FileMonitor();
  public void onCreate/onRename/onDelete(object source, FileSystemEventArgs e)
    {
      try
      {
       FileMon.Watcher.EnableRaisingEvents = false;
      }
      catch
      {
       /* Exception Code */
      }
      finally
      {
       FileMon.Watcher.EnableRaisingEvents = true;
      }
    }
  }

问题:谁能告诉我为什么抛出异常以及如何解决它?

4

1 回答 1

9

几周前我遇到了同样的问题。我发现您需要在设置其他任何内容之前设置路径。因此,在您声明对象之后:

FileSystemWatcher watchfolder = new FileSystemWatcher();
watchfolder.Path = ConfigurationManager.AppSettings["MonitorPath"];

您可以在此处阅读更多内容: 为 Windows 创建文件观察服务

我希望这有帮助

于 2011-08-26T15:55:54.080 回答