具有文件名关键字过滤器的 FileSystemWatcher 特定文件

FileSystemWatcher specific files with filename keywords filter

我正在使用以下代码使用 FileSystemWatcher class 监视本地系统上的文件。我想做的是只观看我在关键字中指定的那些文件名(可以是逗号分隔的字符串或 txt 文件)。 请指引我正确的方向。

   FileSystemWatcher objWatcher = new FileSystemWatcher(); 
   objWatcher.Filter = "*.*"; 
   objWatcher.Changed += new FileSystemEventHandler(OnChanged); 

   private static void OnChanged(object source, FileSystemEventArgs e) 
   { 
     string strFileExt = getFileExt(e.FullPath); 
   } 

谢谢和问候

FileSystemWatcher 组件提供了 PathFilter 属性 来标识您要观看的文件。您可以在 Filter 属性 中使用通配符来监视多个文件,但除此之外,没有任何内置功能可以同时监视任意一组文件。来自 Filter property documentation:不支持使用多个过滤器,例如“.txt|.doc”。

您可能需要为列表中的每个项目创建一个不同的 FileSystemWatcher

虽然 FileSystemWatcher 不支持该功能,但您可以通过在引发事件后过滤文件名来获得该功能。您将无法使用像“.”这样的过滤器,但是例如,如果您想要所有 xml 和 txt 文件,您可以执行 {".xml", ".txt"}

FileSystemWatcher objWatcher = new FileSystemWatcher(); 
objWatcher.Changed += new FileSystemEventHandler(OnChanged); 

string[] filters = new string[] { "test", "blah", ".exe"}; //this needs to be a member of the class so it can be accessed from the Changed event

private static void OnChanged(object source, FileSystemEventArgs e) 
{ 
    if (filters.Any(e.FullPath).Contains))
    {     
        string strFileExt = getFileExt(e.FullPath); 
    }
}

这应该让您对如何操作有一个基本的了解。