2013-03-26 84 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參考。