您的位置:首页 > 编程语言 > C#

C# 监控某一个文件的更改,并触发相关操作

2013-01-04 15:23 579 查看
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);

        }

    }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  .Net C#