我试图递归地获取给定目录中所有子目录的列表,因为现有命令显然不够好。 我可以成功获取目录,但似乎无法离开递归算法。我敢肯定,一定会有一种我看不到的简单方法。任何帮助都会很棒!
public static public void directorySearch(ref List<DirectoryInfo> subs, ref DirectoryInfo dir, ref List<FileInfo> fileEntries, ref int k)
{
do
{
foreach (DirectoryInfo elements in dir.GetDirectories())
{
subs.Add(elements);
}
k++;
DirectoryInfo fi = subs[k];
directorySearch(ref subs, ref fi, ref fileEntries, ref k);
} while (??????);
//This will be used once function is working to get files in all directories
/*
foreach (FileInfo f in dir.GetFiles()
{
fileEntries.Add(f);
}*/
}
答案 0 :(得分:3)
您不需要为此循环。使用using System.Collections.Generic
这将递归搜索:
public static IEnumerable<DirectoryInfo> GetSubdirectories(string path)
{
return new DirectoryInfo(path).EnumerateDirectories("*",SearchOption.AllDirectories);
}
答案 1 :(得分:3)
只需尝试以下操作即可获取目录:
public static IEnumerable<DirectoryInfo> DirectorySearch(DirectoryInfo dir)
{
return
dir
.GetDirectories()
.SelectMany(x => DirectorySearch(x))
.StartWith(dir);
}
然后您可以执行DirectorySearch("C:\My\Path").SelectMany(x => x.GetFiles())
来获取文件。
或者您可以使用此:
public static IEnumerable<DirectoryInfo> DirectorySearch(DirectoryInfo dir)
{
yield return dir;
foreach (DirectoryInfo x in dir.GetDirectories())
foreach (DirectoryInfo y in DirectorySearch(x))
yield return y;
}
甚至是这样:
public static List<DirectoryInfo> DirectorySearch(DirectoryInfo dir)
{
List<DirectoryInfo> subs = new List<DirectoryInfo>();
subs.Add(dir);
foreach (DirectoryInfo x in dir.GetDirectories())
{
foreach (DirectoryInfo y in DirectorySearch(x))
{
subs.Add(y);
}
}
return subs;
}
答案 2 :(得分:-1)
您需要检查当前正在处理的目录是否实际具有子目录。如果是,则执行subs.Add(elements)
,否则,您return
。那就是导致函数在结束时停止的原因。
foreach (DirectoryInfo elements in dir.GetDirectories())
{
subs.Add(elements);
}
k++;
DirectoryInfo fi = subs[k];
if (fi[k].GetDirectories().length > 0)
{
directorySearch(ref subs, ref fi, ref fileEntries, ref k);
} else {
return;
}
我只是在脑海中写下了这个,所以您将不得不调试它,但是它会让您对如何处理这个想法有所了解。