c# 判断文件是否发生了变化

2020-08-19 11:19:01 浏览数 (1)

监控d盘下的所有.txt文件的修改

代码语言:javascript复制
 {
            FileSystemWatcher watcher = new FileSystemWatcher();
            try
            {
                watcher.Path = @"d:Test";
            }
            catch (ArgumentException e)
            {
                Console.WriteLine(e.Message);
                return;
            }
 
            //设置监视文件的哪些修改行为
            watcher.NotifyFilter = NotifyFilters.LastAccess
                | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
 
 
            watcher.Filter = "*.txt";
 
            watcher.Changed  = new FileSystemEventHandler(OnChanged);
            watcher.Created  = new FileSystemEventHandler(OnChanged);
            watcher.Deleted  = new FileSystemEventHandler(OnChanged);
            watcher.Renamed  = new RenamedEventHandler(OnRenamed);
 
            watcher.EnableRaisingEvents = true;
 
            Console.WriteLine(@"Press 'q' to quit app.");
 
            while (Console.Read() != 'q');
        }
 
        static void OnChanged(object source, FileSystemEventArgs e)
        {
            Console.WriteLine("File:{0} {1}!", e.FullPath, e.ChangeType);
        }
 
        static void OnRenamed(object source, RenamedEventArgs e)
        {
            Console.WriteLine("File:{0} renamed ton{1}", e.OldFullPath, e.FullPath);
        }

0 人点赞