【31】C# FileSystemWatcher文件和文件夹监控

简介

FileSystemWatcher这个类用于当目录或目录中的文件发生更改时,侦听文件系统更改通知并引发事件。

使用场景

需要即时的知道文件的更改,获取第三方系统创建的文件等等。

代码示例

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace filewatcher
{
    class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher();
            //获取应用程序的路劲,监听的文件夹路径
            fsw.Path= System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;

            //获取或设置要监视的更改类型
            //LastAccess 最后读的日期
            //LastWrite 最后写的日期
            //FileName 文件名
            //DirectoryName 目录名
            //Attributes 文件或者文件夹属性
            //size 大小
            //Security 安全设置
            fsw.NotifyFilter= NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.Attributes| NotifyFilters.Size|NotifyFilters.Security;

            //文件类型,支持通配符,“*.txt”只监视文本文件
            fsw.Filter = "";

            //设置是否级联监视指定路径中的子目录
            fsw.IncludeSubdirectories = true;

            //添加事件
            fsw.Changed += OnChanged;
            fsw.Created += OnCreated;
            fsw.Deleted += OnDeleted;
            fsw.Renamed += OnRenamed;

            // 开始监听
            fsw.EnableRaisingEvents = true;

            Console.WriteLine("按q退出!");
            while (Console.Read() != 'q') ;

            //FileSystemEventArgs
            //Name 受影响的文件名称
            //FullPath 受影响的文件或文件夹的完整路径
            //ChangeType 获取受影响的文件或目录的发生的事件类型
            void OnChanged(object source, FileSystemEventArgs e)
            {
                Console.Write(e.Name+"文件被改变……\r\n");
            }

            void OnCreated(object source, FileSystemEventArgs e)
            {
                Console.Write(e.Name+"文件被创建……\r\n");
            }

            void OnDeleted(object source, FileSystemEventArgs e)
            {
                Console.Write(e.Name+"文件被删除……\r\n");
            }

            //RenamedEventArgs
            //Name 获取受影响的文件或目录的新名称
            //OldName 获取受影响的文件或目录的旧名称
            //FullPath 获取受影响的文件或目录的完全限定的路径
            //OldFullPath 获取受影响的文件或目录的前一个完全限定的路径
            //ChangeType 获取受影响的文件或目录的发生的事件类型
            void OnRenamed(object source, RenamedEventArgs r)
            {
                Console.Write(r.OldName+"文件被重命名……"+ r.Name+"\r\n");
            }
        }
    }
}

效果预览

【31】C# FileSystemWatcher文件和文件夹监控
2019-04-25-230324.png

参考资料

https://docs.microsoft.com/en-us/dotnet/api/system.io.filesystemwatcher?redirectedfrom=MSDN&view=netframework-4.8