在上一次讲过了FileSystemWatcher 实时监控文件的增加、修改、重命名和删除,具体怎么实现就不再去阐述,参考如下文
C# FileSystemWatcher 实时监控文件的增加、修改、重命名和删除实例
但只是实现了单个目录和全部或单类文件的监控,示例中通过两行代码来设置文件系统监视程序的过滤器。
fileSystemWatcher.Path = “监控路径”;
fileSystemWatcher.Filter = “*.*”;
但我并不希望监控全部文件和目录,而是指定多种文件类型和不同的目录,怎么实现呢?按习惯尝试以下操作,都是不能实现的:
fileSystemWatcher.Path = “监控路径1|监控路径2”;
fileSystemWatcher.Filter = "*.txt | *.doc | *.docx |*.xls"| *.xlsx"
fileSystemWatcher.Path = “监控路径1,监控路径2”;
fileSystemWatcher.Filter = "*.txt | *.doc | *.docx |*.xls"| *.xlsx"
fileSystemWatcher.Path = “监控路径1;监控路径2”;
fileSystemWatcher.Filter = "*.txt ;*.doc;*.docx;*.xls;*.xlsx";
这可能是Filter属性一次只支持一个filter,不支持使用多个filter,Path属性也应该是一样。那怎么办呢?我想到的有二种方法可以实现:
一、Filter全部文件*.*,然后在事件中过滤所需的文件类型
这种方法就是在fileSystemWatcher的Created、Changed、Renamed、Deleted事件中先过滤所需的文件类型,然后再执行想要的操作,下面以Changed事件为例。
private static void OnChanged(object source, FileSystemEventArgs e)
{
string strPath = Path.GetDirectoryName(e.FullPath);
string strFileExt = Path.GetExtension(e.FullPath);
if(strPath == "目录")
{
if (Regex.IsMatch(strFileExt, @"\.txt)|\.doc", RegexOptions.IgnoreCase))
{
//执行想要的操作
}
}
}
二、对不同目录和文件类型分别创建不同的fileSystemWatcher
注意:附件的实例源码就是这种方式
首先定义二个字符串集合来保存目录和文件类型:
public List<string> paths = new List<string>();
public List<string> filters = new List<string>();
再来为不同的目录和文件类型创建fileSystemWatcher,然后将它们全部绑定到同一组事件处理程序:
foreach (string p in paths)
{
foreach (string f in filters)
{
fileSystemWatcher = new FileSystemWatcher();
if (fileSystemWatcher.EnableRaisingEvents) Stop();
fileSystemWatcher.IncludeSubdirectories = true;
fileSystemWatcher.Filter = f;
fileSystemWatcher.Path = p;
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);
fileSystemWatcher.EnableRaisingEvents = true;
}
}
这里有一个问题要注意:监控开始后,停止时要把所有创建的fileSystemWatcher都停止掉才行。不然再开启时就会重复出现监控记录。处理方法如下:定义一个fileSystemWatcher集合watchers,在创建fileSystemWatcher时增加到watchers.Add(fileSystemWatcher),停止时把watchers集合全部停掉。
public List<FileSystemWatcher> watchers = new List<FileSystemWatcher>();
foreach (FileSystemWatcher watcher in watchers)
{
if (watcher.EnableRaisingEvents)
{
watcher.Changed -= new FileSystemEventHandler(FileSystemWatcher_EventHandler);
watcher.Created -= new FileSystemEventHandler(FileSystemWatcher_EventHandler);
watcher.Deleted -= new FileSystemEventHandler(FileSystemWatcher_EventHandler);
watcher.Renamed -= new RenamedEventHandler(FileSystemWatcher_Renamed);
watcher.Error -= new ErrorEventHandler(FileSystemWatcher_Error);
watcher.EnableRaisingEvents = false;
}
}
完成后效果如图
至于这二种方法那一种的效率更高,资源占用又怎样,大家自己试试吧!