使用C#(.NET),如何在给定目录搜索掩码的情况下搜索文件系统,如下所示:(?)
\\server\Scanner\images\*Images\*\*_*
例如,我需要先找到所有顶级目录:
\\server\Scanner\images\Job1Images
\\server\Scanner\images\Job2Images
...然后我需要继续进行搜索掩码:
\\server\Scanner\images\Job1Images\*\*_*
\\server\Scanner\images\Job2Images\*\*_*
这似乎并不太复杂,但我无法弄清楚我的生活......
如上所述,我正在使用C#和.NET。搜索可以尝试查找目录或文件。 (即* .txt,或< *目录>)
答案 0 :(得分:2)
像这样:
顶级目录:
//get Top level
string[] TopLevel = Directory.GetDirectories(path);
然后你将不得不使用通配符模式对此文件夹执行resursive功能, 例如:
// Only get subdirectories that begin with the letter "p."
string pattern = "p*";
string[] dirs = folder.GetDirectories(path, pattern);
我建议你使用通配符来获取数组输出,你会发现 如果使用resursive函数或直接查询路径,这是最好的方法。
答案 1 :(得分:1)
编辑:啊,.NET 4的新功能,所以你不必做递归功能(感谢Matthew Brubaker)
IEnumerable<String> matchingFilePaths2 = System.IO.Directory.EnumerateFiles(@"C:\some folder to start in", filePatternToMatchOn, System.IO.SearchOption.AllDirectories);
第一个答案:
//get all files that have an underscore - searches all folders under the start folder
List<String> matchingFilePaths = new List<string>();
String filePatternToMatchOn = "*_*";
FileUtilities.GetAllFilesMatchingPattern(@"C:\some folder to start in", ref matchingFilePaths, filePatternToMatchOn);
...
public static void GetAllFilesMatchingPattern(String pathToGetFilesIn, ref List<String> fullFilePaths, String searchPattern)
{
//get all files in current directory that match the pattern
String[] filePathsInCurrentDir = Directory.GetFiles(pathToGetFilesIn, searchPattern);
foreach (String fullPath in filePathsInCurrentDir)
{
fullFilePaths.Add(fullPath);
}
//call this method recursively for all directories
String[] directories = Directory.GetDirectories(pathToGetFilesIn);
foreach (String path in directories)
{
GetAllFilesMatchingPattern(path, ref fullFilePaths, searchPattern);
}
}
答案 2 :(得分:1)
public static IEnumerable<string> GetImages()
{
//For each "*Image" directory
foreach (var jobFolder in Directory.EnumerateDirectories(@"\\server\Scanner\images", "*Images"))
{
//For each first level subdirectory
foreach (var jobSubFolder in Directory.EnumerateDirectories(jobFolder))
{
//Enumerate each file containing a '_'
foreach (var filePath in Directory.EnumerateFiles(jobSubFolder, "*_*", SearchOption.TopDirectoryOnly))
{
yield return filePath;
}
}
}
}
仅枚举每个“* Image”目录的第一级子目录中的文件。
最后,您可以将其用于:
foreach (var path in GetImages())
{
Console.WriteLine(path);
}