[英]Return a list of Directory (Folder) names that match a partial string
I need someone to point me in the right direction.我需要有人为我指明正确的方向。
Goal:目标:
Return a list of Folder Names in a path that contain a string in their name.返回路径中包含字符串的文件夹名称列表。 For example: The Path has a Directory named Pictures_New and Videos_New.例如: Path 有一个名为 Pictures_New 和 Videos_New 的目录。 The string I am searching with is "Pictures_" and "Videos_".我正在搜索的字符串是“图片_”和“视频_”。
It all works with one string parameter being passed as a search string.这一切都适用于作为搜索字符串传递的一个字符串参数。 My problem is getting it to work with multiple filters.我的问题是让它与多个过滤器一起工作。 I know it is easily done with file names and extensions.我知道使用文件名和扩展名很容易完成。
This is being passed to GetFolders()
:这将传递给GetFolders()
:
string[] filterStrings = { "Pictures_", "Videos_" }
Rest of my code:我的其余代码:
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;
}
You can use Linq SelectMany
to parse your list of filters and return a list of the results with Directory.GetDirectories();
您可以使用 Linq SelectMany
来解析过滤器列表并使用Directory.GetDirectories();
返回结果列表Directory.GetDirectories();
It will of course return all the Sub Directories that match the filter.它当然会返回与过滤器匹配的所有子目录。 Use just "*".只使用“*”。
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;
}
try:尝试:
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);
}
Looks like you're not looping through each of your filter strings:看起来您没有遍历每个过滤器字符串:
var folders = new List<string>();
foreach (var filterString in filterStrings)
{
folders.AddRange(Directory.EnumerateDirectories(path, filterString, searchOption););
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.