2013-03-26 67 views
1

我想使用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; 
} 

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

+0

无论是下面的答案的是正确的。所以指向他们两个 – user726720 2013-03-26 12:14:40

回答

1

EnableRaisingEvents是默认false,你可以尝试把它改变之前AMD为每个文件夹的新的观察者:

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

单个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参考。