2013-04-10 99 views
0

我使用FileSystemWatcher來監視文件系統。它可以觀看特定的文件夾或驅動器。使用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; 
} 

使用Filesystem Watcher - Multiple folders

+0

展示你的工作.. – 2013-04-10 11:04:02

回答

1

的一種方法是,以枚舉所有的目錄,並通過對他們每個人的使用FileSystemWatcher看着他們。

但它會消耗大量的資源。因此,您可以對此鏈接進行替代查看:Filewatcher for the whole computer (alternative?)

+0

你的意思是所有的'root'文件夾或所有文件夾和子文件夾(遞歸)? – 2013-04-10 11:07:05

+0

「很多資源」我假設你的意思是「OutOfMemoryException」.. – 2013-04-10 11:07:17

1

您可以使用IncludeSubdirectories查看整個系統到邏輯驅動器。 試試這個代碼,

string[] drives = Environment.GetLogicalDrives(); 

foreach(string drive in drives) 
{ 
    FileSystemWatcher watcher = new FileSystemWatcher(); 
    watcher.Path = drive; 
    watcher.IncludeSubdirectories = true; 
    watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 
        | NotifyFilters.FileName | NotifyFilters.DirectoryName; 

    watcher.Filter = "*.txt"; 

    watcher.Changed += new FileSystemEventHandler(OnChanged); 
    watcher.Created += new FileSystemEventHandler(OnChanged); 
    watcher.Deleted += new FileSystemEventHandler(OnChanged); 
    watcher.Renamed += new RenamedEventHandler(OnRenamed); 

    watcher.EnableRaisingEvents = true; 
} 
相關問題