文件系统守望者 - 多个文件夹多个、文件系统、文件夹、守望者

2023-09-07 08:57:40 作者:不服来打姐

我想用FileSystemWatcher的如下监视多个文件夹。我下面code只是看一个文件夹:

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

但上面的code监视一个文件夹中,并没有对其它文件夹影响。什么是什么原因呢?

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

推荐答案

EnableRaisingEvents 是默认的,你可以尽量把它之前更改的AMD做出新的观察者为每个文件夹:

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