~$ 存档

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

 

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:\001.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);
        }
    }
}

 

posted on 2020-09-02 11:28  LuoTian  阅读(214)  评论(0编辑  收藏  举报