好多时候,我们都需要知道某些目录下的文件什么时候被修改、删除过等,如果能用miniFilter驱动过滤来做的话当然是最好不过了,这是内核级别的,当然也比较复杂。如果只是简单的记录就没必要用驱动过滤级别的来做了,用FileSystemWatcher来做就要简单得多。
FileSystemWatcher组件可以监视文件系统,并在文件系统发生改变时作出反应。FileSystemWatcher 常用于文件系统变更的监控,当被监视的文件夹目录被创建、修改、重命名或删除时,会触发以下事件:
- Created: 当新建文件或者文件夹
- Changed:当文件或者文件夹已经完成修改
- Renamed:当文件或者文件夹完成重命名
- Deleted:当文件或者文件夹被删除
- Error:当变更过程发生错误
下面我们一起来完成一个文件监控实例。
一、实例化FileSystemWatcher类,并注册监听事件
//创建一个FileSystemWatcher,并设置其属性
FileSystemWatcher fileSystemWatcher = new FileSystemWatcher();
//设置监控的路径
fileSystemWatcher.Path = “监控路径”;
//是否监控指定路径中的子目录
fileSystemWatcher.IncludeSubdirectories = true;
//启用
fileSystemWatcher.EnableRaisingEvents = true;
//注册监听事件,Created、Changed、Deleted三个事件传递的参数是一样的,我们就用同一个方法来处理就可以了
fileSystemWatcher.Changed += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
fileSystemWatcher.Created += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
fileSystemWatcher.Deleted += new FileSystemEventHandler(FileSystemWatcher_EventHandler);
fileSystemWatcher.Renamed += new RenamedEventHandler(FileSystemWatcher_Renamed);
fileSystemWatcher.Error += new ErrorEventHandler(FileSystemWatcher_Error);
二、事件处理
FileSystemEventArgs 对象成员有:Name、OldName、ChangeType、FullPath、OldFullPath等,看名就明白是什么了,这里不做过多解释。
//创建一个FileSystemWatcher,并设置其属性
FileSystemWatcher fileSystemWatcher = new FileSyst