【问题标题】:FileSystemWatcher specific files with filename keywords filter带有文件名关键字过滤器的 FileSystemWatcher 特定文件
【发布时间】:2015-12-18 08:57:08
【问题描述】:

我正在使用以下代码使用 FileSystemWatcher 类来监视本地系统上的文件。我想做的是只查看我在关键字中指定的那些文件名(可以是逗号分隔的字符串或 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); 
   } 

感谢和问候

【问题讨论】:

标签: c# .net regex filesystemwatcher


【解决方案1】:

虽然 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); 
    }
}

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

【讨论】:

  • 谢谢大家,我希望有一个选项可以将多个标记为答案。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2014-10-26
    相关资源
    最近更新 更多