C B*_*rgs 2 .net c# directory search
我正在 Visual Studio 2012 中使用 C# 和 .net 4.0 构建 Windows 应用程序。
该程序的功能之一是搜索满足给定搜索条件的所有文件,该条件通常(但并不总是)包含通配符。
搜索条件在运行时未知;它是从 Excel 电子表格导入的。
可能的搜索条件可包括以下内容:
我尝试使用Directory.EnumerateFiles:
IEnumerable<string> matchingFilePaths = System.IO.Directory.EnumerateFiles(@"C:\", selectedItemPath[0], System.IO.SearchOption.AllDirectories);
Run Code Online (Sandbox Code Playgroud)
然而这只适用于上面的情况 2。尝试在文件夹名称中使用Directory.EnumerateFiles通配符会导致“非法字符”豁免。
我希望 .net 中有一个可以用来进行文件搜索的单行代码。通配符的数量和目录结构的深度在运行时是未知的,可以想象,搜索可能必须深入一百个文件夹,每个文件夹都包含未知数量的通配符。(这就是问题的关键)。尽量避免嵌套 for 循环的数量过多。
我在这里阅读了解决方案,但这似乎不适用于任意文件夹结构。
既然您已经回答了自己的问题,我想我会将我的尝试发布给任何可能发现此问题并且不想使用 powershell 的其他人。它全部都是延迟加载的,因此在您拥有大型文件系统并且匹配大量文件的情况下,其性能将是最佳的。
用法示例:
string pattern = @"C:\Users\*\Source\Repos\*\*.cs";
foreach (var st in GetAllMatchingPaths(pattern))
Console.WriteLine(st);
Run Code Online (Sandbox Code Playgroud)
解决方案:
public static IEnumerable<string> GetAllMatchingPaths(string pattern)
{
char separator = Path.DirectorySeparatorChar;
string[] parts = pattern.Split(separator);
if (parts[0].Contains('*') || parts[0].Contains('?'))
throw new ArgumentException("path root must not have a wildcard", nameof(parts));
return GetAllMatchingPathsInternal(String.Join(separator.ToString(), parts.Skip(1)), parts[0]);
}
private static IEnumerable<string> GetAllMatchingPathsInternal(string pattern, string root)
{
char separator = Path.DirectorySeparatorChar;
string[] parts = pattern.Split(separator);
for (int i = 0; i < parts.Length; i++)
{
// if this part of the path is a wildcard that needs expanding
if (parts[i].Contains('*') || parts[i].Contains('?'))
{
// create an absolute path up to the current wildcard and check if it exists
var combined = root + separator + String.Join(separator.ToString(), parts.Take(i));
if (!Directory.Exists(combined))
return new string[0];
if (i == parts.Length - 1) // if this is the end of the path (a file name)
{
return Directory.EnumerateFiles(combined, parts[i], SearchOption.TopDirectoryOnly);
}
else // if this is in the middle of the path (a directory name)
{
var directories = Directory.EnumerateDirectories(combined, parts[i], SearchOption.TopDirectoryOnly);
var paths = directories.SelectMany(dir =>
GetAllMatchingPathsInternal(String.Join(separator.ToString(), parts.Skip(i + 1)), dir));
return paths;
}
}
}
// if pattern ends in an absolute path with no wildcards in the filename
var absolute = root + separator + String.Join(separator.ToString(), parts);
if (File.Exists(absolute))
return new[] { absolute };
return new string[0];
}
Run Code Online (Sandbox Code Playgroud)
PS:它不会匹配目录,只会匹配文件,但如果需要,您可以轻松修改它。
| 归档时间: |
|
| 查看次数: |
2513 次 |
| 最近记录: |