1. 程式人生 > 其它 >c# 兩種方法監聽檔案、目錄變化

c# 兩種方法監聽檔案、目錄變化

  1. 使用FileSystemWatcher 初始化傳遞要監聽的目錄, 在過濾中過濾檔案(可以使用萬用字元)
 public class FileListenerServer
    {
        private FileSystemWatcher _watcher;

        public FileListenerServer(string path)
        {
            this._watcher = new FileSystemWatcher();
            _watcher.Path = path;
            _watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.DirectoryName;
            _watcher.IncludeSubdirectories = true;
            _watcher.Created += new FileSystemEventHandler(FileWatcher_Created);
            _watcher.Changed += new FileSystemEventHandler(FileWatcher_Changed);
            _watcher.Deleted += new FileSystemEventHandler(FileWatcher_Deleted);
            _watcher.Renamed += new RenamedEventHandler(FileWatcher_Renamed);
        }


        public void Start()
        {

            this._watcher.EnableRaisingEvents = true;
            Console.WriteLine("檔案監控已經啟動...");

        }

        public void Stop()
        {

            this._watcher.EnableRaisingEvents = false;
            this._watcher.Dispose();
            this._watcher = null;

        }

        protected void FileWatcher_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("新增:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);

        }
        protected void FileWatcher_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("變更:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
        }
        protected void FileWatcher_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("刪除:" + e.ChangeType + ";" + e.FullPath + ";" + e.Name);
        }
        protected void FileWatcher_Renamed(object sender, RenamedEventArgs e)
        {

            Console.WriteLine("重新命名: OldPath:{0} NewPath:{1} OldFileName{2} NewFileName:{3}", e.OldFullPath, e.FullPath, e.OldName, e.Name);

        }
    }
  1. 使用PhysicalFileProvider,其實本質上使用的FileSystemWatcher
public class PhysicalFileProviderHelper
    {

        public static PhysicalFileProvider Listen(string filePath)
        {
            FileInfo? file = new FileInfo(filePath);
            PhysicalFileProvider? watch = new PhysicalFileProvider(file.Directory.FullName);

            ChangeToken.OnChange(
                () => watch.Watch(file.Name),
                () => ShowChange(watch)
                );

            return watch;
        }

        private static void ShowChange(PhysicalFileProvider watch)
        {
            //TODO
            Console.WriteLine("change");
        }
    }