using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var watcher1 = new FileWatch(@"d:\data.txt");
            watcher1.Start();
            var watcher2 = new FileWatch(@"e:\123.txt");
            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)
            {
                var 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)
        {
            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);
        }
    }
}
                    
                
                
            
        
浙公网安备 33010602011771号