In a previous example, I have showed how to use the FileSystemWatcher
class to monitor a directory. But there are times that we need to monitor multiple directories and if any changes are available, invoke a given method.
We can do that by using the following method. First create a class. We’ll call this classWatcher
.
1: public class Watcher 2: { 3: 4: public string Directory { get; set; } 5: public string Filter { get; set; } 6: 7: 8: private Delegate _changeMethod; 9: 10: public Delegate ChangeMethod 11: { 12: get { return _changeMethod; } 13: set { _changeMethod = value; } 14: } 15: 16: FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); 17: 18: public Watcher(string directory, string filter, Delegate invokeMethod) 19: { 20: this._changeMethod = invokeMethod; 21: this.Directory = directory; 22: this.Filter = Filter; 23: } 24: 25: 26: public void StartWatch() 27: { 28: 29: 30: fileSystemWatcher.Filter = this.Filter; 31: fileSystemWatcher.Path = this.Directory; 32: fileSystemWatcher.EnableRaisingEvents = true; 33: 34: fileSystemWatcher.Changed += new FileSystemEventHandler(fileSystemWatcher_Changed); 35: } 36: 37: void fileSystemWatcher_Changed(object sender, FileSystemEventArgs e) 38: { 39: if (_changeMethod != null) 40: { 41: _changeMethod.DynamicInvoke(sender, e); 42: } 43: } 44: }
And we can use it to monitor multiple directories as shown below (for this example, I have used a console application and I am only considering the change event):
1: class Program 2: { 3: delegate void invokeMethodDelegate(object sender, FileSystemEventArgs e); 4: 5: static void Main(string[] args) 6: { 7: 8: invokeMethodDelegate mymethod = new invokeMethodDelegate(InvokeMethod); //公用的全局函数 9: Watcher w1 = new Watcher(@"C:\Directory1", "*.*", mymethod); //这里先后创建两个监视对象,指向共同的全局函数 10: w1.StartWatch(); 11: 12: Watcher w2 = new Watcher(@"D:\Directory2", "*.*", mymethod); 13: w2.StartWatch(); 14: 15: string zRetVal = Console.ReadLine(); 16: 17: 18: } 19: 20: static void InvokeMethod(object sender, FileSystemEventArgs e)//公用的全局函数 21: { 22: Console.WriteLine("Change in file {0}", e.FullPath); 23: } 24: }
所以,看到C#的事件机制,还是比较让人感觉亲切。