【问题标题】:Add FileSystemEventHandler dynamically to FileSystemWatcher将 FileSystemEventHandler 动态添加到 FileSystemWatcher
【发布时间】:2014-12-17 10:14:38
【问题描述】:

我正在尝试创建一个 Windows 服务,该服务可以从包含 FileSystemWatcher 的所有信息的数据库表中检索“热文件夹”列表(扫描目录、文件过滤器等)。

但是当我想将 Created 事件处理程序添加到 FileSystemWatcher 时,这让我遇到了问题。

id  hotFolderName   directory   fileFilter  engineModule    includeSubdirs
1   PDFinvoices     c:/pdf      *.pdf       pdfModule       0
2   FlatFiles       c:/flat     *.txt       flatModule      1

因此,对于表中的每个帖子,它都会使用上述设置创建一个 FileSystemWatcher,但我的问题是当我想将 EventHandler 绑定到它时。我如何动态地做到这一点?

所以在这种情况下,我想做:

fileSystemWatcher1.Created += new FileSystemEventHandler(dbResultSet("engineModule"));

这有可能以某种方式做到吗?我知道我还需要一个名为 pdfModule 的函数,但这没问题。我只是希望能够添加更多模块,但不必更改上面的语法。

在这种情况下,pdfModule 可能不在主类中,我在想我为每个模块创建一个类。像 pdfModule、flatModule ...你明白了。

【问题讨论】:

    标签: c# dynamic module filesystemwatcher eventhandler


    【解决方案1】:

    您必须创建自己的文件监控器类并在其中包装观察器属性,对于事件,您可以像下面这样处理它

    this.yourwatcher.Created += new FileSystemEventHandler(this.yourwatcher_Created);
    this.yourwatcher.EnableRaisingEvents = true;
    

    在服务启动事件中,您可以从数据库获取所有信息,并可以执行以下操作

    this.filemonitor[0] = new CustomFileMonitor("pdfModule");  // This will configure watcher properties for PDF file types and attach event.
    this.filemonitor[0].Start();
    

    为每种文件夹类型创建文件监视器的新实例。

    【讨论】:

      猜你喜欢
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 2023-03-07
      • 1970-01-01
      • 1970-01-01
      • 2013-03-10
      • 2011-10-05
      • 2013-12-17
      相关资源
      最近更新 更多