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”

    

    运行结果:

    

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

发布了515 篇原创文章 · 获赞 135 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/liyazhen2011/article/details/103990295
今日推荐