FileSystemWatcher
常用属性:
Path:获取或设置要监视的目录的路径
Filter:获取或设置筛选字符串,用于确定在目录中监视哪些文件
NotifyFilter:获取或设置要监视的更改类型。
EnableRaisingEvents:获取或设置一个值,该值指示是否启用此组件。
常用事件:
OnChanged:执行Changed,Created,Deleted时引发改事件
OnRenamed:执行重命名时引发改事件
监控代码:(源码.rar)
C#文件监控
1 #region 监控文件 2 public void Run() 3 { 4 //创建文件监控对象 5 FileSystemWatcher watcher = new FileSystemWatcher(); 6 //设置监控目录 7 watcher.Path = path; 8 //定义监控类型 9 watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite 10 | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime; 11 //定义监控的文件类型 12 watcher.Filter = "*.*"; 13 14 //绑定监控事件 15 watcher.Changed += new FileSystemEventHandler(OnChanged); 16 watcher.Created += new FileSystemEventHandler(OnChanged); 17 watcher.Deleted += new FileSystemEventHandler(OnChanged); 18 watcher.Renamed += new RenamedEventHandler(OnRenamed); 19 20 //true表示开始监控,启用监控;false表示取消监控 21 watcher.EnableRaisingEvents = true; 22 } 23 24 private void OnChanged(object source, FileSystemEventArgs e) 25 { 26 27 string changedInfo = string.Format("File: {0} {1}", e.FullPath, e.ChangeType); 28 //因为UI上的线程非安全的,所以要使用Invoke 29 this.Invoke(new Method(AddItem),changedInfo); 30 } 31 32 private void OnRenamed(object source, RenamedEventArgs e) 33 { 34 35 string changedInfo = string.Format("File: {0} renamed to {1}", e.OldFullPath, e.FullPath); 36 //因为UI上的线程非安全的,所以要使用Invoke 37 this.Invoke(new Method(AddItem), changedInfo); 38 39 } 40 //把监控到的信息添加到ListBox上 41 private void AddItem(string item) 42 { 43 listBox1.Items.Add(item); 44 } 45 #endregion