【问题标题】:Filesystem Watcher - Multiple folders文件系统观察程序 - 多个文件夹
【发布时间】:2013-03-26 11:05:47
【问题描述】:

我想使用 filesystemwatcher 来监控多个文件夹,如下所示。我下面的代码只监视一个文件夹:

public static void Run()
{
     string[] args = System.Environment.GetCommandLineArgs();

     if (args.Length < 2)
     {
          Console.WriteLine("Usage: Watcher.exe PATH [...] [PATH]");
          return;
     }
     List<string> list = new List<string>();
     for (int i = 1; i < args.Length; i++)
     {
          list.Add(args[i]);
     }

     foreach (string my_path in list)
     {
          WatchFile(my_path);
     }

     Console.WriteLine("Press \'q\' to quit the sample.");
     while (Console.Read() != 'q') ;
}

private static void WatchFile(string watch_folder)
{
    watcher.Path = watch_folder;

    watcher.NotifyFilter = NotifyFilters.LastWrite;
    watcher.Filter = "*.xml";
    watcher.Changed += new FileSystemEventHandler(convert);
    watcher.EnableRaisingEvents = true;
}

但是上面的代码监控一个文件夹,对另一个文件夹没有影响。这是什么原因?

【问题讨论】:

  • 以下两个答案都是正确的。所以指向他们两个

标签: c# .net filesystemwatcher


【解决方案1】:

单个FileSystemWatcher 只能监控单个文件夹。您需要多个 FileSystemWatchers 才能实现此功能。

private static void WatchFile(string watch_folder)
{
    // Create a new watcher for every folder you want to monitor.
    FileSystemWatcher fsw = new FileSystemWatcher(watch_folder, "*.xml");

    fsw.NotifyFilter = NotifyFilters.LastWrite;

    fsw.Changed += new FileSystemEventHandler(convert);
    fsw.EnableRaisingEvents = true;
}

请注意,如果您想稍后修改这些观察者,您可能希望通过将每个创建的 FileSystemWatcher 添加到列表或其他东西来维护对它的引用。

【讨论】:

    【解决方案2】:

    EnableRaisingEvents 是默认的false,你可以尝试把它放在 Changed 之前,并且为每个文件夹创建一个新的 watcher:

    FileSystemWatcher watcher = new FileSystemWatcher();
    watcher.Path = watch_folder;
    watcher.NotifyFilter = NotifyFilters.LastWrite;
    watcher.Filter = "*.xml";
    watcher.EnableRaisingEvents = true;
    watcher.Changed += new FileSystemEventHandler(convert);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多