具有通配符筛选的绝对路径

本文关键字:路径 筛选 通配符 | 更新日期: 2023-09-27 18:36:33

>我有一个字符串列表,其中包含出于操作目的应忽略的文件。所以我很好奇如何处理有通配符的情况。

例如,我的字符串列表中可能的输入是:

C:'Windows'System32'bootres.dll
C:'Windows'System32'*.dll

我认为第一个示例很容易处理,我可以只做一个字符串等于检查(忽略大小写)以查看文件是否匹配。但是,我不确定如何确定给定文件是否与列表中的通配符表达式匹配。

介绍一下我正在做的事情的背景。允许用户将文件复制到某个位置/从某个位置复制文件,但是,如果该文件与我的字符串列表中的任何文件匹配,则我不想允许复制。

可能有一个必须更好的方法来处理这个问题。

我要排除的文件是从配置文件中读入的,并且我收到尝试复制的路径的字符串值。似乎我拥有完成任务所需的所有信息,这只是最佳方法的问题。

具有通配符筛选的绝对路径

IEnumerable<string> userFiles = Directory.EnumerateFiles(path, userFilter);
// a combination of any files from any source, e.g.:
IEnumerable<string> yourFiles = Directory.EnumerateFiles(path, yourFilter);
// or new string[] { path1, path2, etc. };
IEnumerable<string> result = userFiles.Except(yourFiles);

解析以分号分隔的字符串:

string input = @"c:'path1'*.dll;d:'path2'file.ext";
var result = input.Split(";")
                  //.Select(path => path.Trim())
                  .Select(path => new
                  {
                      Path = Path.GetFullPath(path), //  c:'path1
                      Filter = Path.GetFileName(path) // *.dll
                  })
                  .SelectMany(x => Directory.EnumerateFiles(x.Path, x.Filter));

您可以使用Directory.GetFiles()并使用路径的文件名来查看是否有任何匹配的文件:

string[] filters = ...
return filters.Any(f => 
    Directory.GetFiles(Path.GetDirectoryName(f), Path.GetFileName(f)).Length > 0);

更新:
我确实完全错了。您有一组包含通配符的文件筛选器,并希望根据这些通配符检查用户输入。您可以在评论中使用@hometoast提供的解决方案:

// Configured filter:
string[] fileFilters = new [] 
{ 
  @"C:'Windows'System32'bootres.dll", 
  @":'Windows'System32'*.dll" 
}
// Construct corresponding regular expression. Note Regex.Escape!
RegexOptions options = RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase;
Regex[] patterns = fileFilters
  .Select(f => new Regex("^" + Regex.Escape(f).Replace("''*", ".*") + "$", options))
  .ToArray(); 
// Match against user input:
string userInput = @"c:'foo'bar'boo.far";
if (patterns.Any(p => p.IsMatch(userInput)))
{ 
  // user input matches one of configured filters
}