我需要有人指出我正确的方向。
目标:
在名称中包含字符串的路径中返回文件夹名称的列表。例如:Path有一个名为Pictures_New和Videos_New的目录。我正在搜索的字符串是“Pictures_”和“Videos _”。
一切都可以使用一个字符串参数作为搜索字符串传递。我的问题是让它与多个过滤器一起使用。我知道用文件名和扩展名很容易做到。
这是传递给GetFolders()
:
string[] filterStrings = { "Pictures_", "Videos_" }
我的其余代码:
public IEnumerable<string> GetFolders(string path, string[] filterStrings, SearchOption searchOption = SearchOption.AllDirectories)
{
IEnumerable<string> folders = Directory.EnumerateDirectories(path, "Pictures_*.*", searchOption);
var resultFolders = new List<string>();
if(filterStrings.Length > 0)
{
foreach (var foldername in folders)
{
string folderName = Path.GetFileName(Path.GetDirectoryName(foldername));
if (string.IsNullOrEmpty(folderName) || Array.IndexOf(filterStrings, "*" + folderName) < 0)
{
// This leaves us only with the Directory names. No paths.
var b = (foldername.Substring(foldername.LastIndexOf(@"\") + 1));
resultFolders.Add(b);
}
}
}
return resultFolders;
}
答案 0 :(得分:2)
您可以使用Linq SelectMany
来解析过滤器列表,并使用Directory.GetDirectories();
返回结果列表
它当然会返回与过滤器匹配的所有子目录。只使用“*”。
public IEnumerable<string> GetFolders(string path, string[] filterStrings, SearchOption searchOption = SearchOption.AllDirectories)
{
List<string> resultFolders = filterStrings
.SelectMany(flt => Directory.GetDirectories(path, flt, searchOption))
.ToList();
return resultFolders;
}
答案 1 :(得分:1)
尝试:
var patterns = new[] { "Pictures_*", "Videos_*" };
var dirsFound = new List<string>();
foreach (var dir in patterns.Select(pattern => Directory.GetDirectories(@"my path", pattern).ToArray()))
{
dirsFound.AddRange(dir);
}
答案 2 :(得分:0)
您似乎没有遍历每个过滤字符串:
var folders = new List<string>();
foreach (var filterString in filterStrings)
{
folders.AddRange(Directory.EnumerateDirectories(path, filterString, searchOption););
}