由於在網上找不到文件監聽多個目錄的解決辦法,後本身摸索出來,在這裏分享下使用當心得,也爲本身鞏固一下。數組
FileSystemWatcher的使用辦法在MSDN上記錄的很詳細http://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher.aspxide
(C#的技術建議你們沒有用過的先參考一下MSDN)ui
上代碼spa
1 //string str; 2 public void WatcherFiles() 3 { 4 try 5 { 6 //str = "\\\\172.17.1.85\\shareforder\\DPM"; 7 //Run(str); 8 Run(); 9 } 10 catch (Exception ex) 11 { 12 Logger.Log(LogLevel.Local, ex.ToString()); 13 } 14 } 15 /// <summary> 16 /// 監聽多個文件目錄 17 /// </summary> 18 [PermissionSet(SecurityAction.Demand, Name = "FullTrust")] 19 public static void Run() 20 { 21 //改成泛型獲取文件列表最好(實驗Demo) 22 string[] paths = { "\\\\192.168.0.1\\shareforder\\filepath1", "\\\\192.168.0.2\\filepath2" }; 23 FileSystemWatcher[] wathcerArr = new FileSystemWatcher[paths.Count()]; 24 for (int i = 0; i < paths.Count(); i++) 25 { 26 wathcerArr[i] = new FileSystemWatcher(); 27 wathcerArr[i].Path = paths[i]; 28 wathcerArr[i].NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 29 | NotifyFilters.FileName | NotifyFilters.DirectoryName; 30 wathcerArr[i].Changed += new FileSystemEventHandler(OnChanged); 31 wathcerArr[i].Created += new FileSystemEventHandler(OnChanged); 32 wathcerArr[i].Deleted += new FileSystemEventHandler(OnChanged); 33 wathcerArr[i].Renamed += new RenamedEventHandler(OnRenamed); 34 35 // Begin watching. 36 wathcerArr[i].EnableRaisingEvents = true; 37 wathcerArr[i].IncludeSubdirectories = true; 38 } 39 40 Console.WriteLine("Press \'q\' to quit the sample."); 41 while (Console.Read() != 'q') ; 42 }
方法很簡單,只須要建立一個 FileSystemWatcher的數組,分別添加屬性、事件,完活!code