You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何确定FileSystemWatcher事件匹配的具体文件筛选器?

如何确定FileSystemWatcher触发事件匹配的筛选器?

你当前使用FileSystemWatcher的代码如下:

using watcher = new FileSystemWatcher(@"C:\path\to\folder");

watcher.NotifyFilter = NotifyFilters.Attributes
                     | NotifyFilters.CreationTime
                     | NotifyFilters.DirectoryName
                     | NotifyFilters.FileName
                     | NotifyFilters.LastAccess
                     | NotifyFilters.LastWrite
                     | NotifyFilters.Security
                     | NotifyFilters.Size;

watcher.Created += OnCreated;
watcher.Error += OnError;

foreach(string filter in filters) 
{
    watcher.Filters.Add(filter);
}

watcher.IncludeSubdirectories = false;
watcher.EnableRaisingEvents = true;

对应的OnCreated事件处理程序:

private static void OnCreated(object sender, FileSystemEventArgs e)
{
    string value = $"Created: {e.FullPath}";
    Console.WriteLine(value);
}

你希望在事件触发时,知道具体匹配的是Filters列表中的哪一个筛选器(比如创建f1_demo.txt时,匹配的是f1_*.txt还是f2_*.txt)。


解决方案:自行判断匹配的筛选器

FileSystemWatcher本身不会在事件参数中返回触发事件的筛选器,因为它底层依赖系统API进行文件监听,不会跟踪具体匹配的筛选规则。你需要在事件处理程序中,手动检查文件名与筛选器的匹配关系。

实现步骤:

  1. 从事件参数中提取文件名(而非完整路径)
  2. 遍历FileSystemWatcher的Filters列表,逐个检查文件名是否符合筛选器的通配符规则
  3. 收集所有匹配的筛选器(可能存在多个筛选器匹配同一文件的情况)

代码示例:

首先添加一个通配符匹配的辅助方法,用于将DOS风格的通配符(*、?)转换为正则表达式进行匹配:

private static bool MatchesWildcard(string inputFileName, string filterPattern)
{
    // 将通配符转换为正则表达式:*替换为任意字符,?替换为单个字符
    string regexPattern = "^" + Regex.Escape(filterPattern)
                          .Replace("\\*", ".*")
                          .Replace("\\?", ".") + "$";
    // 忽略大小写匹配(与FileSystemWatcher的筛选器行为一致)
    return Regex.IsMatch(inputFileName, regexPattern, RegexOptions.IgnoreCase);
}

然后修改OnCreated事件处理程序,实现筛选器匹配判断:

private static void OnCreated(object sender, FileSystemEventArgs e)
{
    var watcher = sender as FileSystemWatcher;
    if (watcher == null) return;

    string fileName = Path.GetFileName(e.FullPath);
    List<string> matchedFilters = new List<string>();

    foreach (string filter in watcher.Filters)
    {
        if (MatchesWildcard(fileName, filter))
        {
            matchedFilters.Add(filter);
        }
    }

    if (matchedFilters.Any())
    {
        Console.WriteLine($"Created: {e.FullPath}, 匹配的筛选器: {string.Join(", ", matchedFilters)}");
    }
    else
    {
        Console.WriteLine($"Created: {e.FullPath}, 未匹配任何筛选器");
    }
}

注意事项:

  • FileSystemWatcher的筛选器使用DOS风格通配符,上述辅助方法的匹配逻辑与原生行为保持一致
  • 单个文件可能匹配多个筛选器(例如同时存在*.txt和f1_*.txt时,f1_demo.txt会匹配两个),代码中会收集所有匹配项
  • 若你的筛选器包含路径相关规则(不过FileSystemWatcher的Filters仅支持文件名筛选),需要调整匹配逻辑

内容的提问来源于stack exchange,提问作者Om Palsanawala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 22:15:35