我需要使用部分名称在目录中搜索文件。
前:
Directory : c:\Path
Filename : Error_005296-895632-12563.xml
Partial file name: 005296-895632-12563
我在下面尝试过。
Directory.GetFiles("c:\Path", "*005296-895632-12563*.xml", SearchOption.AllDirectories).
但它没有工作
示例文件名是:
Error_005296-895632-12563.xml
005296-895632-12563_Response.xml
Duplicate_005296-895632-12563_Response.xml
答案 0 :(得分:1)
您可以创建扩展方法并传递要查找的部分名称数组。
像这样调用扩展方法
DirectoryInfo dir = new DirectoryInfo(@"c:\demo");
FileInfo[] files = dir.GetFilesBypartialName("Anc_def_", "ABC_123", "12_qweqweqw_123").ToArray();
下面是扩展方法
public static class DirectoryFindFile
{
public static IEnumerable<FileInfo> GetFilesBypartialName(this DirectoryInfo dirInfo, params string[] partialFilenames)
{
if (partialFilenames == null)
throw new ArgumentNullException("partialFilenames");
var lstpartialFilenames = new HashSet<string>(partialFilenames, StringComparer.OrdinalIgnoreCase);
return dirInfo.EnumerateFiles()
.Where(f => lstpartialFilenames.Contains(f.Name));
}
public static IEnumerable<FileInfo> GetFilesBypartialFilenamesAllDir(this DirectoryInfo dirInfo, params string[] partialFilenames)
{
if (partialFilenames == null)
throw new ArgumentNullException("partialFilenames");
var lstpartialFilenames = new HashSet<string>(partialFilenames, StringComparer.OrdinalIgnoreCase);
return dirInfo.EnumerateFiles("*.*", SearchOption.AllDirectories)
.Where(f => lstpartialFilenames.Contains(f.Name));
}
}
答案 1 :(得分:0)
这是我用来搜索目录的扩展函数
public static IEnumerable<string> GetFiles(string path, string searchPatternExpression = "", SearchOption searchOption = SearchOption.AllDirectories)
{
Regex reSearchPattern = new Regex(searchPatternExpression);
return Directory.EnumerateFiles(path, "*", searchOption).Where(file => reSearchPattern.IsMatch(System.IO.Path.GetExtension(file)));
}