【发布时间】:2015-07-06 11:45:06
【问题描述】:
我需要能够从一个目录和子目录中获取所有文件,但我想给用户选择子目录深度的选项。 即,不只是当前目录或所有目录,而且他应该能够选择 1,2,3,4 目录等的深度。
我见过很多遍历目录树的示例,但似乎都没有解决这个问题。就个人而言,我对递归感到困惑......(我目前使用的)。我不确定如何在递归函数期间跟踪深度。
任何帮助将不胜感激。
谢谢, 大卫
这是我当前的代码(我找到了here):
static void FullDirList(DirectoryInfo dir, string searchPattern, string excludeFolders, int maxSz, string depth)
{
try
{
foreach (FileInfo file in dir.GetFiles(searchPattern))
{
if (excludeFolders != "")
if (Regex.IsMatch(file.FullName, excludeFolders, RegexOptions.IgnoreCase)) continue;
myStream.WriteLine(file.FullName);
MasterFileCounter += 1;
if (maxSz > 0 && myStream.BaseStream.Length >= maxSz)
{
myStream.Close();
myStream = new StreamWriter(nextOutPutFile());
}
}
}
catch
{
// make this a spearate streamwriter to accept files that failed to be read.
Console.WriteLine("Directory {0} \n could not be accessed!!!!", dir.FullName);
return; // We alredy got an error trying to access dir so dont try to access it again
}
MasterFolderCounter += 1;
foreach (DirectoryInfo d in dir.GetDirectories())
{
//folders.Add(d);
// if (MasterFolderCounter > maxFolders)
FullDirList(d, searchPattern, excludeFolders, maxSz, depth);
}
}
【问题讨论】:
-
stackoverflow.com/questions/6141648/… 可能会给你一个提示
-
注意递归?将参数添加到递归函数,在每个子文件夹调用时递增。这样你就知道自己有多深了。
-
@Thorarins,谢谢!我不敢相信我没有找到 - 我搜索了很多! - 我正在研究它,并将回帖