C#FileSystemWatcher类的Changed事件触发多次

 public static void Main(string[] args)
        {


            //创建一个新的FileSystemWatcher并设置其属性
            FileSystemWatcher watcher = new FileSystemWatcher();
            watcher.Path = "F:\\";
            /*监视LastAcceSS和LastWrite时间的更改以及文件或目录的重命名*/
            watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite |
                   NotifyFilters.FileName | NotifyFilters.DirectoryName;
            //只监视文本文件
            watcher.Filter = "*.txt";
            //添加事件句柄
            //当由FileSystemWatcher所指定的路径中的文件或目录的
            //大小、系统属性、最后写时间、最后访问时间或安全权限
            //发生更改时,更改事件就会发生
            watcher.Changed += new FileSystemEventHandler(OnChanged);
            //由FileSystemWatcher所指定的路径中文件或目录被创建时,创建事件就会发生
            //watcher.Created += new FileSystemEventHandler(OnChanged);
            //当由FileSystemWatcher所指定的路径中文件或目录被删除时,删除事件就会发生
            //watcher.Deleted += new FileSystemEventHandler(OnChanged);
            //当由FileSystemWatcher所指定的路径中文件或目录被重命名时,重命名事件就会发生
            //watcher.Renamed += new RenamedEventHandler(OnRenamed);
            //开始监视
            watcher.EnableRaisingEvents = true;
            //等待用户退出程序
            //Console.WriteLine(DateTime.Now+",Press\'q\' to quit the sample.");
            while (Console.Read() != 'q') ;
        }
        //定义事件处理程序
        public static void OnChanged(object sender, FileSystemEventArgs e)
        {
            var watcher = sender as FileSystemWatcher;
            watcher.EnableRaisingEvents = false;
            //指定当文件被更改、创建或删除时要做的事
            Console.WriteLine(DateTime.Now+",file:" + e.FullPath + "" + e.ChangeType);
            watcher.EnableRaisingEvents = true;
        }

解决方法:

只需要在开始处理时先做:watcher.EnableRaisingEvents = false;

结束后再做:watcher.EnableRaisingEvents = true;

转载于:https://www.cnblogs.com/ChaunceyWan/p/11357789.html

你可能感兴趣的:(C#FileSystemWatcher类的Changed事件触发多次)