• C# FileSystemWatcher 实时监控文件的增加、修改、重命名和删除实例


           好多时候,我们都需要知道某些目录下的文件什么时候被修改、删除过等,如果能用miniFilter驱动过滤来做的话当然是最好不过了,这是内核级别的,当然也比较复杂。如果只是简单的记录就没必要用驱动过滤级别的来做了,用FileSystemWatcher来做就要简单得多。

           FileSystemWatcher组件可以监视文件系统,并在文件系统发生改变时作出反应。FileSystemWatcher 常用于文件系统变更的监控,当被监视的文件夹目录被创建、修改、重命名或删除时,会触发以下事件:

    1. Created: 当新建文件或者文件夹
    2. Changed:当文件或者文件夹已经完成修改
    3. Renamed:当文件或者文件夹完成重命名
    4. Deleted:当文件或者文件夹被删除
    5. Error:当变更过程发生错误

    下面我们一起来完成一个文件监控实例。

    一、实例化FileSystemWatcher类,并注册监听事件           

                 //创建一个FileSystemWatcher,并设置其属性
                FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); 
                //设置监控的路径
                fileSystemWatcher.Path = “监控路径”;
                //是否监控指定路径中的子目录
                fileSystemWatcher.IncludeSubdirectories = true;
                //启用
                fileSystemWatcher.EnableRaisingEvents = true;

                //注册监听事件,Created、Changed、Deleted三个事件传递的参数是一样的,我们就用同一个方法来处理就可以了
                fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
                fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
                fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
                fileSystemWatcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
                fileSystemWatcher.Error += new ErrorEventHandler(FileSystemWatcher_Error);

    二、事件处理

               FileSystemEventArgs 对象成员有:Name、OldName、ChangeType、FullPath、OldFullPath等,看名就明白是什么了,这里不做过多解释。

                 //创建一个FileSystemWatcher,并设置其属性
                FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(); 
                //设置监控的路径
                fileSystemWatcher.Path = “监控路径”;
                //是否监控指定路径中的子目录
                fileSystemWatcher.IncludeSubdirectories = true;
                //启用
                fileSystemWatcher.EnableRaisingEvents = true;

                //Created、Changed、Deleted三个事件的处理方法
                private static void FileSystemWatcher_EventHandler(object sender, FileSystemEventArgs e)
                {
                            Invoke(new Action(new Action(() =>
                            {
                                   Console.WriteLine(e.Name+e.FullPath);
                            })));
                }
                //重命名事件的处理方法
                private void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
                {
                            Invoke(new Action(new Action(() =>
                            {
                                   Console.WriteLine(e.OldName+e.Name+e.FullPath);
                            })));
                } 
               //错误事件的处理方法
                private void FileSystemWatcher_Error(object sender, ErrorEventArgs e)
                {
                            Invoke(new Action(new Action(() =>
                            {
                                   Console.WriteLine(e.ToString()));
                            })));
                }

                这里需要注意一个问题:因为FileSystemWatcher类本身就是一个多线程的控件,在实例化一个FileSystemWatcher时就自动创建了一个线程,在事件处理的方法中需要使用委托的方式封送到主线程中处理。

    //声明传递文件Created、Changed、Deleted对象和委托,用于文件增加、删除、修改时更新UI界面
    private delegate void setLogDelegate(FileSystemEventArgs e); 

    三、展示监控记录

    监控的记录可以保存到文件和数据库中,这里就增加一个listView来展示就好了

     

    代码:

    1. using System;
    2. using System.Collections.Generic;
    3. using System.ComponentModel;
    4. using System.Data;
    5. using System.Drawing;
    6. using System.IO;
    7. using System.Linq;
    8. using System.Runtime.InteropServices;
    9. using System.Text;
    10. using System.Threading.Tasks;
    11. using System.Windows.Forms;
    12. namespace FileWatcher
    13. {
    14. public partial class Form1 : Form
    15. {
    16. private delegate void renameDelegate(RenamedEventArgs e); //声明传递RenamedEventArgs对象和委托,用于文件Renamed时更新UI界面
    17. private delegate void setLogDelegate(FileSystemEventArgs e); //声明传递文件Created、Changed、Deleted对象和委托,用于文件增加、删除、修改时更新UI界面
    18. private FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
    19. private ColumnHeader chTime = new ColumnHeader();
    20. private ColumnHeader chEvent = new ColumnHeader();
    21. private ColumnHeader chFile = new ColumnHeader();
    22. private ColumnHeader chPath = new ColumnHeader();
    23. public Form1()
    24. {
    25. InitializeComponent();
    26. chTime.TextAlign = HorizontalAlignment.Center;
    27. chTime.Width = 130;
    28. chTime.Text = "时间";
    29. this.listViewInfo.Columns.Add(chTime);
    30. chEvent.TextAlign = HorizontalAlignment.Center;
    31. chEvent.Width = 80;
    32. chEvent.Text = "事件";
    33. this.listViewInfo.Columns.Add(chEvent);
    34. chFile.Width = 270;
    35. chFile.Text = "文件";
    36. this.listViewInfo.Columns.Add(chFile);
    37. chPath.Width = this.listViewInfo.Width - chTime.Width - chEvent.Width - chFile.Width - 21;
    38. chPath.Text = "位置";
    39. this.listViewInfo.Columns.Add(chPath);
    40. ColumnHeader chEnd = new ColumnHeader();
    41. chEnd.Width = 17;
    42. chEnd.Text = "";
    43. this.listViewInfo.Columns.Add(chEnd);
    44. this.listViewInfo.View = View.Details;
    45. this.listViewInfo.GridLines = true;
    46. fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
    47. fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
    48. fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
    49. fileSystemWatcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
    50. fileSystemWatcher.Error += new ErrorEventHandler(FileSystemWatcher_Error);
    51. fileSystemWatcher.IncludeSubdirectories = true;
    52. fileSystemWatcher.EnableRaisingEvents = true;
    53. }
    54. #region 文件增加、删除、修改时被调用的处理方法
    55. private void FileSystemWatcher_EventHandler(object sender, FileSystemEventArgs e)
    56. {
    57. if (listViewInfo.InvokeRequired) //判断是否跨线程
    58. {
    59. listViewInfo.Invoke(new setLogDelegate(SetLog), new object[] { e });//使用委托将方法封送到UI主线程处理
    60. }
    61. }
    62. private void SetLog(FileSystemEventArgs e)
    63. {
    64. string strLog = "";
    65. switch (e.ChangeType.ToString())
    66. {
    67. case "Created":
    68. strLog = "文件创建";
    69. break;
    70. case "Changed":
    71. strLog = "文件修改";
    72. break;
    73. case "Deleted":
    74. strLog = "文件删除";
    75. break;
    76. default:
    77. strLog = e.ChangeType.ToString();
    78. break;
    79. }
    80. ListViewItem lvi = new ListViewItem();
    81. lvi.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    82. lvi.SubItems.Add(strLog);
    83. lvi.SubItems.Add(e.Name);
    84. lvi.SubItems.Add(e.FullPath.Replace(e.Name,""));
    85. listViewInfo.Items.Add(lvi);
    86. }
    87. #endregion
    88. #region 重命名方法
    89. private void FileSystemWatcher_Renamed(object sender, RenamedEventArgs e)
    90. {
    91. if (listViewInfo.InvokeRequired)
    92. {
    93. listViewInfo.Invoke(new renameDelegate(SetRenamedLog), new object[]{e});
    94. }
    95. }
    96. private void SetRenamedLog(RenamedEventArgs e)
    97. {
    98. //listViewInfo.Items.Add(string.Format("重命名:{0} 被换名为:{1}, {2}", e.OldName, e.Name, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
    99. ListViewItem lvi = new ListViewItem();
    100. lvi.Text = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    101. lvi.SubItems.Add("文件重命名");
    102. lvi.SubItems.Add(e.OldName + "被换名为:" + e.Name);
    103. lvi.SubItems.Add(e.FullPath.Replace(e.Name, ""));
    104. listViewInfo.Items.Add(lvi);
    105. }
    106. #endregion
    107. #region 错误事件的方法
    108. private void FileSystemWatcher_Error(object sender, ErrorEventArgs e)
    109. {
    110. if (listViewInfo.InvokeRequired) //判断是否跨线程
    111. {
    112. //使用委托处理
    113. Invoke(new Action(new Action(() =>
    114. {
    115. listViewInfo.Items.Add(string.Format("文件出错:{0}, {1}", e.ToString(), DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
    116. })));
    117. }
    118. }
    119. #endregion
    120. }
    121. }

    完整例子下载

  • 相关阅读:
    项目干系人管理的10个关键原则
    【Codeforces】Educational Codeforces Round 156 [Rated for Div. 2]
    操作简单的BI数据分析软件有哪些?实际体验如何?
    Java-Gui编程
    刨根问底 Kubernetes -- CNI (三)Multus
    Redis的高可用
    Postman、Apifox、Apipost用哪个?
    图解机器学习 | 降维算法详解
    docker部署项目常见的问题及解决方案
    在线考试系统
  • 原文地址:https://blog.csdn.net/xgh815/article/details/126193809