FileSystemWatcher 监控文件变化

以编程方式观察文件
FileSystemWatcher类
通过System.IO.NotifyFilters 枚举来决定需要FileSystemWatcher类型监控文件的行为
public enum NotifyFilters
{
Attributes,
CreationTime,
DirectoryName,
FileName,
LastAccess,
LastWrite,
Security,
Size
}

使用FileSystemWatcher类型的第一步是设置 Path 属性,以制定需要监控的文件所在的文件夹的名字,还有就是定义需要监控文件的扩展名的Filter属性
第二步使用FileSystemEventHandler委托关联的事件来实现Changed、Created和Deleted事件的处理方法。
这个委托符合下列模式:
void MyNotificationHandler(object source,FileSystemEventArgs e);
同样Renamed事件也可以通过RenamedEventHandler
void MyRenamedHandler(object source,RenamedEventArgs e);
(1) FileSystemWatcher watcher=new FileSystemWatcher();
watcher.Path=@"C:myfolder"; //指定监控路径
(2) watcher.NotifyFilter=NotifyFilters.LastAccess|NotfiyFilters.LastWrite|NotifyFilters.FileName|NotifyFilters.DirectoryName; //设置需要留意的事情
(3) watcher.Filter="*.txt"; //只观察文本文件
(4) watcher.Changed+=new FileSystemEventHandler(OnChanged); //增加事件处理程序
watcher.Created+=new FileSystemEventHandler(OnChanged);
watcher.Deleted+=new FileSystemEventHandler(OnChanged);
watcher.Renamed+=new RenamedEventHandler(OnRenamed);
(5) watcher.EnableRaisingEvents=true; //开始观察目录

原文地址:https://www.cnblogs.com/sundh1981/p/15369313.html