• FileSystemWatcher使用


    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    
    namespace ConsoleApplication1
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                var watcher2 = new FileWatch(@"E:01.BLK");
                watcher2.Start();
                Console.Read();
            }
        }
    
        public class FileWatch
        {
    
            private readonly FileSystemWatcher __fileWatcher;
            private readonly HashSet<string> __hstbWatcher;
    
            public FileWatch(string filePath)
            {
                __hstbWatcher = new HashSet<string>();
                if (__fileWatcher == null)
                {
                    FileInfo file = new FileInfo(filePath);
                    __fileWatcher = new FileSystemWatcher(file.DirectoryName) { Filter = file.Name, NotifyFilter = NotifyFilters.LastWrite };
                    __fileWatcher.Changed += _watcher_Changed;
                }
            }
    
            public void Start()
            {
                __fileWatcher.EnableRaisingEvents = true;
            }
    
            public void Stop()
            {
                __fileWatcher.EnableRaisingEvents = false;
            }
    
            private void _watcher_Changed(object sender, FileSystemEventArgs e)
            {
                Console.WriteLine("执行一次...");
                if (__hstbWatcher.Any(q => q.Equals(e.FullPath, StringComparison.CurrentCultureIgnoreCase)))
                {
                    lock (__hstbWatcher)
                    {
                        __hstbWatcher.Remove(e.FullPath);
                        return;
                    }
                }
                lock (__hstbWatcher)
                {
                    __hstbWatcher.Add(e.FullPath);
                }
                Console.WriteLine(e.FullPath + " " + e.ChangeType);
            }
        }
    }
  • 相关阅读:
    Windows常用cmd命令总结
    电脑UEFI启动是什么?
    PHP 7天前的时间戳
    背景图片
    SQLite/SQL Server Compact Toolbox
    修改浏览器下拉条颜色和粗细
    thinkphp5 apache htaccess配置文件重写
    thinkphp5 token验证
    英文共享js
    ul高度为0的解决方法
  • 原文地址:https://www.cnblogs.com/tinaluo/p/13600830.html
Copyright © 2020-2023  润新知