FileWatcher.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using Y.Utils.DataUtils.Collections;
  7. namespace Y.Utils.IOUtils.FileManUtils
  8. {
  9. /// <summary>
  10. /// 文件更改通知
  11. /// </summary>
  12. public class FileWatcher
  13. {
  14. private bool _IsStart = false;
  15. private List<FileSystemWatcher> Watchers = new List<FileSystemWatcher>();
  16. /// <summary>
  17. /// 当前运行状态
  18. /// </summary>
  19. public bool IsStart { get { return _IsStart; } }
  20. public delegate void FileWatcherEventHandler(object sender, FileWatcherEventArgs args);
  21. public FileWatcher()
  22. {
  23. DriveInfo[] drives = DriveInfo.GetDrives().Where(x => x.IsReady && (x.DriveType == DriveType.Fixed || x.DriveType == DriveType.Removable)).ToArray();
  24. if (ListTool.HasElements(drives))
  25. {
  26. foreach (var d in drives)
  27. {
  28. FileSystemWatcher fsw = new FileSystemWatcher(d.Name);
  29. fsw.Created += CreatedEvent;//创建文件或目录
  30. fsw.Changed += ChangedEvent;//更改文件或目录
  31. fsw.Deleted += DeletedEvent;//删除文件或目录
  32. fsw.Renamed += RenamedEvent;//重命名文件或目录
  33. fsw.IncludeSubdirectories = true;
  34. fsw.NotifyFilter = (NotifyFilters)383;
  35. Watchers.Add(fsw);
  36. }
  37. }
  38. }
  39. public void Start()
  40. {
  41. _IsStart = true;
  42. if (ListTool.HasElements(Watchers))
  43. {
  44. foreach (var w in Watchers)
  45. {
  46. w.EnableRaisingEvents = true;
  47. }
  48. }
  49. }
  50. public void Stop()
  51. {
  52. _IsStart = false;
  53. if (ListTool.HasElements(Watchers))
  54. {
  55. foreach (var w in Watchers)
  56. {
  57. w.EnableRaisingEvents = false;
  58. }
  59. }
  60. }
  61. private void CreatedEvent(object sender, FileSystemEventArgs e)
  62. {
  63. }
  64. private void ChangedEvent(object sender, FileSystemEventArgs e)
  65. {
  66. }
  67. private void DeletedEvent(object sender, FileSystemEventArgs e)
  68. {
  69. }
  70. private void RenamedEvent(object sender, RenamedEventArgs e)
  71. {
  72. }
  73. }
  74. }