FileSystemWatcher 监控文件变化

    本文测试了FileSystemWatcher 类监控文件变化。

using System;
using System.Security.Permissions;
using System.IO;

namespace ConsoleApp1
{
    public class FileStateWatcher
    {    
        [PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
        public static int Run()
        {
            FileSystemWatcher fsWatcher = new FileSystemWatcher();
            fsWatcher.Path = "E:\\Test";

            fsWatcher.NotifyFilter = NotifyFilters.LastAccess |    //上一次打开的日期。 
                                     NotifyFilters.LastWrite |     //上一次写入内容的日期
                                     NotifyFilters.FileName |      //文件名
                                     NotifyFilters.DirectoryName | //目录名
                                     NotifyFilters.Size;           //大小

            //监听子目录
            fsWatcher.IncludeSubdirectories = true;
            //监听文件类型
            fsWatcher.Filter = "*.txt";

            //添加事件处理
            fsWatcher.Changed += new FileSystemEventHandler(OnChanged);
            fsWatcher.Created += new FileSystemEventHandler(OnCreated);
            fsWatcher.Deleted += new FileSystemEventHandler(OnDeleted);
            fsWatcher.Renamed += new RenamedEventHandler(OnRenamed);

            fsWatcher.EnableRaisingEvents = true;       
            return 0;
        }
        //修改时的处理
        private static void OnChanged(Object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
        }
        //重命名时的处理
        private static void OnRenamed(Object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
        }
        //删除时的处理
        private static void OnDeleted(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
        }
        //创建时的处理
        private static void OnCreated(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File: {0} {1}", e.FullPath, e.ChangeType);
        }
    };

    class Program
    {
        static void Main(string[] args)
        {
            FileStateWatcher.Run();
            // 输入q结束程序
            Console.WriteLine("Press q to quit the sample.");
            while (Console.Read() != 'q') ;
        }
    }
}

    上例中监控的目录是“E:\\Test”,在此目录下创建txt文件,命名为“log.txt”

    

    运行结果:

    

    本例仅仅打印了发生变化的文件名及变化类型。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值