Filesystem Watcher - Multiple folders

陌路散爱 提交于 2019-12-11 12:02:18

问题


I want to use filesystemwatcher to monitor multiple folders as follows. My below code only watches one folder:

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;
}

But the above code monitors one folder and has not effect on the other folder. What is the reason for that ?


回答1:


EnableRaisingEvents is default false, you can try to put it before the Changed amd make a new watcher for each folder:

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



回答2:


A single FileSystemWatcher can only monitor a single folder. You will need to have multiple FileSystemWatchers in order to implement this.

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;
}

Note that if you want to modify these watchers later, you may want to maintain a reference to each created FileSystemWatcher by adding it to a list or something.



来源:https://stackoverflow.com/questions/15635477/filesystem-watcher-multiple-folders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!