使用C#如何监控选定文件夹中文件的变动情况?

这篇具有很好参考价值的文章主要介绍了使用C#如何监控选定文件夹中文件的变动情况?。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录✨

1、前言

2、效果

3、具体实现

​ 页面设计

​ 全部代码

​ FileSystemWatcher的介绍

​ FileSystemWatcher的构造函数

​ FileSystemWatcher的属性

​ FileSystemWatcher的事件

4、总结

前言✨

有时候我们会有监控电脑上某一个文件夹中文件变动情况的需求,在本文中,我也会以一个具体的例子,说明在C#中如何使用FileSystemWatcher类来实现上述需求。

效果✨

具体实现✨

如果你对C#如何监控选定文件夹中文件的变动情况感兴趣,可以继续往下阅读。

界面设计

为了更好的演示效果,我这里winform的界面设计如下:

很简单,只有一个button与一个richtextbox,button用来指定被监控的文件,richtextbox用来输出一些信息。

全部代码

namespace FileSystemWatcherDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            // 创建一个 FolderBrowserDialog 实例
            FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();

            // 设置对话框的标题
            folderBrowserDialog.Description = "选择文件夹";

            // 如果用户点击了“确定”按钮
            if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
            {
                richTextBox1.Text = "";
                // 获取用户选择的文件夹路径
                string selectedFolder = folderBrowserDialog.SelectedPath;

                // 提示被监控文件夹路径
                richTextBox1.Text += $"被监控的文件夹为:{selectedFolder}\r\n";

                var watcher = new FileSystemWatcher($"{selectedFolder}");
               
                watcher.NotifyFilter = NotifyFilters.Attributes
                                | NotifyFilters.CreationTime
                                | NotifyFilters.DirectoryName
                                | NotifyFilters.FileName
                                | NotifyFilters.LastAccess
                                | NotifyFilters.LastWrite
                                | NotifyFilters.Security
                                | NotifyFilters.Size;

                watcher.Changed += OnChanged;
                watcher.Created += OnCreated;
                watcher.Deleted += OnDeleted;
                watcher.Renamed += OnRenamed;
                
                watcher.Filter = "*.txt";
                watcher.IncludeSubdirectories = true;
                watcher.EnableRaisingEvents = true;
            }
            else
            {
                MessageBox.Show("您本次没有选择文件夹!!!");
            }
          

           
   
        }

        private void AppendMessageToRichTextBox(string message)
        {
            // 在RichTextBox中添加提示信息        
            richTextBox1.Invoke(new Action(() =>
            {
                richTextBox1.AppendText(message + Environment.NewLine);
            }));
        }

        private void OnChanged(object sender, FileSystemEventArgs e)
        {
            if (e.ChangeType != WatcherChangeTypes.Changed)
            {
                return;
            }
            AppendMessageToRichTextBox($"Changed: {e.FullPath}");
        }

        private void OnCreated(object sender, FileSystemEventArgs e)
        {
            string value = $"Created: {e.FullPath}";
            AppendMessageToRichTextBox($"Created: {e.FullPath}");
        }

        private  void OnDeleted(object sender, FileSystemEventArgs e)
        {
            AppendMessageToRichTextBox($"Deleted: {e.FullPath}");
        }

        private  void OnRenamed(object sender, RenamedEventArgs e)
        {       
            AppendMessageToRichTextBox($"Renamed:");
            AppendMessageToRichTextBox($"    Old: {e.OldFullPath}");
            AppendMessageToRichTextBox($"    New: {e.FullPath} ");           
        }
     
    }
}

FileSystemWatcher的介绍

看过以上代码,会发现核心就是FileSystemWatcher的使用。接下来我将介绍一下C#中的FileSystemWatcher类。

FileSystemWatcher是C#中的一个类,该类可以侦听文件系统更改通知,并在目录或目录中的文件发生更改时引发事件。

FileSystemWatcher的构造函数

该类有三种构造函数,如下所示:

形式 含义
FileSystemWatcher() 初始化 FileSystemWatcher 类的新实例。
FileSystemWatcher(String) 初始化 FileSystemWatcher 类的新实例,给定要监视的目录。
FileSystemWatcher(String, String) 初始化 FileSystemWatcher类的新实例,给定要监视的目录和文件类型。
 var watcher = new FileSystemWatcher($"{selectedFolder}");

本文中我选择的就是第二种构造函数,指定要监视的目录。

FileSystemWatcher的属性

现在介绍一下在本示例中用到的FileSystemWatcher的属性,如下所示:

名称 类型 含义
EnableRaisingEvents bool 设置FileSystemWatcher是否有效
Filter string 设置一个要监控的文件的格式
Filters Collection 设置多个要监控的文件的格式
IncludeSubdirectories bool 获取或设置一个值,该值指示是否应监视指定路径中的子目录
NotifyFilter NotifyFilters 获取或设置要监视的更改的类型
Path string 获取或设置要监视的目录的路径

现在来解释下所用到的代码的含义:

watcher.Filter = "*.txt";

表示要监控的文件为.txt格式。

 watcher.IncludeSubdirectories = true;

表示指定路径中的子目录也要监视。

 watcher.EnableRaisingEvents = true;

表示该对象可以触发事件,也就是还有效。

 watcher.NotifyFilter = NotifyFilters.Attributes
                                | NotifyFilters.CreationTime
                                | NotifyFilters.DirectoryName
                                | NotifyFilters.FileName
                                | NotifyFilters.LastAccess
                                | NotifyFilters.LastWrite
                                | NotifyFilters.Security
                                | NotifyFilters.Size;

设置要监视的更改的类型。NotifyFilter属性的类型为NotifyFilters枚举类型。

NotifyFilters枚举类型:

[System.Flags]
public enum NotifyFilters

指定要在文件或文件夹中监视的更改。

此枚举支持其成员值的按位组合。

该枚举类型包含的值与含义如下所示:

名称 含义
Attributes 文件或文件夹的属性
CreationTime 文件或文件夹的创建时间
DirectoryName 目录名
FileName 文件的名称
LastAccess 文件或文件夹上一次打开的日期
LastWrite 上一次向文件或文件夹写入内容的日期
Security 文件或文件夹的安全设置
Size 文件或文件夹的大小

在这里使用了该枚举类型的按位组合表示这几种更改的类型要受到监视。

FileSystemWatcher的事件

FileSystemWatcher中的事件如下:

名称 含义
Changed 当更改指定 Path 中的文件和目录时发生
Created 当在指定Path 中创建文件和目录时发生
Deleted 删除指定Path中的文件或目录时发生
Renamed 重命名指定 Path中的文件或目录时发生
Error 当 FileSystemWatcher 的实例无法继续监视更改或内部缓冲区溢出时发生
                watcher.Changed += OnChanged;
                watcher.Created += OnCreated;
                watcher.Deleted += OnDeleted;
                watcher.Renamed += OnRenamed;

在这里我使用到了Changed、Created、Deleted和Renamed事件。

我将以Changed 事件为例,详细解释一下:

 watcher.Changed += OnChanged;

这行代码的含义。

我们查看FileSystemWatcher的源代码,Changed事件的代码如下所示:

/// <devdoc>
///    Occurs when a file or directory in the specified <see cref='System.IO.FileSystemWatcher.Path'/> is changed.
/// </devdoc>
public event FileSystemEventHandler? Changed
{
    add
    {
        _onChangedHandler += value;
    }
    remove
    {
        _onChangedHandler -= value;
    }
}

可知将值赋给了_onChangedHandler,我们再来查看_onChangedHandler的定义:

 // Event handlers
 private FileSystemEventHandler? _onChangedHandler;

类型为FileSystemEventHandler?与Changed事件一致,再来看看FileSystemEventHandler?的定义:

 public delegate void FileSystemEventHandler(object sender, FileSystemEventArgs e);

发现是一个参数类型分别为object、FileSystemEventArgs返回值类型为空的委托类型。

object我们知道,那么FileSystemEventArgs又是什么呢?

查看它的源码,截取一部分,如下所示:

public class FileSystemEventArgs : EventArgs
{
     private readonly WatcherChangeTypes _changeType;
     private readonly string? _name;
     private readonly string _fullPath;
     /// <devdoc>
///    Gets one of the <see cref='System.IO.WatcherChangeTypes'/> values.
/// </devdoc>
public WatcherChangeTypes ChangeType
{
    get
    {
        return _changeType;
    }
}

/// <devdoc>
///    Gets the fully qualified path of the affected file or directory.
/// </devdoc>
public string FullPath
{
    get
    {
        return _fullPath;
    }
}


/// <devdoc>
///       Gets the name of the affected file or directory.
/// </devdoc>
public string? Name
{
    get
    {
        return _name;
    }
}
 }

发现FileSystemEventArgs继承自EventArgs,而EventArgs表示包含事件数据的类的基类,因此可以明白FileSystemEventArgs表示为目录事件:Changed, Created, Deleted提供数据的类。

FileSystemEventArgs提供三个数据分别为ChangeType、FullPath、Name。

那ChangeType是什么呢?

查看ChangeType的定义:

 //
 // 摘要:
 //     Changes that might occur to a file or directory.
 [Flags]
 public enum WatcherChangeTypes
 {
     //
     // 摘要:
     //     The creation of a file or folder.
     Created = 1,
     //
     // 摘要:
     //     The deletion of a file or folder.
     Deleted = 2,
     //
     // 摘要:
     //     The change of a file or folder. The types of changes include: changes to size,
     //     attributes, security settings, last write, and last access time.
     Changed = 4,
     //
     // 摘要:
     //     The renaming of a file or folder.
     Renamed = 8,
     //
     // 摘要:
     //     The creation, deletion, change, or renaming of a file or folder.
     All = 15
 }

是一个枚举类型,表示更改的类型。

现在回过头来看:

watcher.Changed += OnChanged;

OnChanged方法如下:

  private void OnChanged(object sender, FileSystemEventArgs e)
  {
      if (e.ChangeType != WatcherChangeTypes.Changed)
      {
          return;
      }
      AppendMessageToRichTextBox($"Changed: {e.FullPath}");
  }

为什么可以将OnChanged方法订阅到watcher.Changed事件上呢?

因为OnChanged方法与watcher.Changed事件中的委托类型FileSystemEventHandler的返回类型和签名是相同的。

OnChanged方法的返回类型与签名如下:

 private void OnChanged(object sender, FileSystemEventArgs e)

FileSystemEventHandler委托类型的定义如下:

 public delegate void FileSystemEventHandler(object sender, FileSystemEventArgs e);

现在已经理解了订阅事件,那么什么时候触发事件呢?

查看FileSystemWatcher的部分源码:

 /// <devdoc>
 ///    Raises the <see cref='System.IO.FileSystemWatcher.Changed'/> event.
 /// </devdoc>
 protected void OnChanged(FileSystemEventArgs e)
 {
     InvokeOn(e, _onChangedHandler);
 }
 private void InvokeOn(FileSystemEventArgs e, FileSystemEventHandler? handler)
 {
     if (handler != null)
     {
         ISynchronizeInvoke? syncObj = SynchronizingObject;
         if (syncObj != null && syncObj.InvokeRequired)
             syncObj.BeginInvoke(handler, new object[] { this, e });
         else
             handler(this, e);
     }
 }

当发生相应的改变时,就会调用FileSystemWatcher类的OnChanged方法,从而触发事件。

总结✨

本文通过一个实例,介绍了如何通过C#中的FileSystemWatcher类实现监控选定的文件夹,希望对你有所帮助。文章来源地址https://www.toymoban.com/news/detail-760718.html

到了这里,关于使用C#如何监控选定文件夹中文件的变动情况?的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Everything如何按时间查找文件和文件夹 everything使用教程

    d: datemodified:2023/07/05 size:10Mb d: dc:2023/07/05 size:10Mb datecreated:date 搜索指定创建日期的文件和文件夹.简写dc: datemodified:date 搜索指定修改日期的文件和文件夹. 简写dm: daterun:date 搜索指定打开时间的文件和文件夹. 简写 dr: recentchange:date 搜索指定最近修改日期的文件和文件夹.简写

    2024年02月13日
    浏览(49)
  • Mac 如何删除文件及文件夹?可以尝试使用终端进行删除

    MacOS 是 Mac 电脑采用的操作系统,你知道 Mac 如何删除文件吗?除了直接将文件或者文件夹拖入废纸篓之外,我们还可以采用终端命令的办法去删除文件,本文为大家总结了 Mac 删除文件方法。 在使用 Mac 电脑的时候为什么要采用命令行删除文件而不是直接文件拖入废纸篓呢?

    2024年03月16日
    浏览(60)
  • c# 文件夹选择 , 文件选择

    c# 文件夹选择 , 文件选择 using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using System.IO; namespace Test07 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, Eve

    2024年02月13日
    浏览(32)
  • 如何在Linux系统中使用SCP命令传输文件和文件夹?

    在Linux系统中,SCP(Secure Copy)是一种用于在本地和远程主机之间安全传输文件和文件夹的命令行工具。它基于SSH协议,并提供了加密和身份验证机制,确保数据的安全性和完整性。 本文将详细介绍如何使用SCP命令在Linux系统中传输文件和文件夹。 SCP命令的基本语法如下: 选

    2024年02月06日
    浏览(40)
  • C#怎么删除指定文件或文件夹

    本文主要介绍了C#如何删除指定文件或文件夹,具有很好的参考价值,希望对大家有所帮助。 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 public static string deleteOneFile( string fileFullPath)          {              // 1、首先判断文件或者文件路径是否存在              i

    2024年02月13日
    浏览(38)
  • 【C#】在Windows资源管理器打开文件夹,并选中指定的文件或文件夹

    因软件里使用了第三方插件,第三方插件的日志文件夹存在路径不止一个,并且可能层级较深。 为便于运维人员和最终用户使用,在界面上增加一个“打开XX文件夹”的按钮,点击时,打开第三方插件日志文件夹所在的上级文件夹,并选中其下级指定名称的若干个文件和文件

    2024年02月14日
    浏览(34)
  • C#实时监测文件夹变化

    在开发各种应用程序时,我们经常需要对文件系统中的文件或文件夹进行实时监测,以便在文件内容改变、文件被创建或删除时能够及时做出反应。在 C# 中,System.IO.FileSystemWatcher 类为我们提供了这样一个强大的功能。 一、引入 FileSystemWatcher 类 首先,在项目中引入 System.IO

    2024年03月15日
    浏览(46)
  • C#怎样创建、移动及遍历文件夹

    一、使用DirectoryInfo类创建文件夹: 1、使用DirectoryInfo前需要引入命名空间: 2、DirectoryInfo类没有静态方法,仅可以用于实例化的对象,  3、判断输入的文件夹名称是否为空,弹出提示框 4、 通过Exists()方法判断要创建的文件夹是否存在 5、创建文件夹:  二、使用DirectoryI

    2024年02月12日
    浏览(29)
  • C#中复制文件夹及文件的两种方法

    现将文件复制的问题整理的知识做了一下总结,以方便自己和大家学习!本节要说的是C#中复制文件夹及文件的两种方法,闲话不说,直接附代码如下: 方法一: 方法二:       方法一 和 方法二 都可以实现文件夹及文件的复制,两者的区别是:方法一的复制并没有包括原文件的根目录

    2024年02月16日
    浏览(27)
  • C#修改解决方案的名称 和解决方案文件夹的名称 ,及项目程序名称,项目文件夹名称

    修改失败了,没有备份就得炸裂,一定要切记 右键项目- 属性 - 应用程序 先将 程序集名称 与 默认命名空间 先修改好 其次,在按组合键ctrl+ f 将原来的项目名称,替换成新的名称; 替换时,一定要针对整个解决方案进行替换 ----切记 关闭解决方案 ,一定要关闭 出现无法加

    2023年04月09日
    浏览(60)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包