gpt4 book ai didi

c# - 在控制深度的同时遍历目录 - C#

转载 作者:行者123 更新时间:2023-12-02 04:19:57 24 4
gpt4 key购买 nike

我需要能够从目录和子目录中获取所有文件,但我想为用户提供选择子目录深度的选项。即,不仅仅是当前目录或所有目录,而且他应该能够选择 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);
}

}

最佳答案

使用可以在每次递归调用时递减的最大深度变量,然后一旦达到所需的深度就不能返回。

static void FullDirList(DirectoryInfo dir, string searchPattern, string excludeFolders, int maxSz, int maxDepth)
{

if(maxDepth == 0)
{
return;
}

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 - 1);
}

}

关于c# - 在控制深度的同时遍历目录 - C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31245015/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com