FileSystemWatcher多个文件目录监听服务
因为在网上找不到文件监听多个目录的解决办法,后自己摸索出来,在这里分享下使用小心得,也为自己巩固一下。
FileSystemWatcher的使用办法在MSDN上记录的很详细http://msdn.microsoft.com/zh-cn/library/system.io.filesystemwatcher.aspx
(C#的技术建议大家没有用过的先参考一下MSDN)
上代码
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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的数组,分别添加属性、事件,完活!