C# 監控某一個文件的更改,並觸發相關操作

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);

        }


    }


}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章