如何限制递归子目录搜索的深度
我有一个功能,当前可以抓取所有文件夹和子文件夹来检查我正在构建的小工具的 ACL,但我正在绞尽脑汁试图弄清楚如何限制它可以达到的深度。例如,您有一个 4 层深的文件夹,但我希望只能获取其中 3 层的 ACL。
目前我已经这样编码了:
private void StepThroughDirectories(string dir)
{
string[] directories = Directory.GetDirectories(dir);
try
{
foreach (string d in Directory.GetDirectories(dir))
{
if (recCount < (int)Depth)
{
GetACLs(d, new DirectoryInfo(d));
pBar.Value += 1;
//MessageBox.Show("Recursive Level: " + counter.ToString());
recCount++;
StepThroughDirectories(d);
}
else
{
recCount--;
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
显然,这并不像以前那么好,因为我已经研究这个问题一段时间了,但如果有人能指出我正确的方向来解决这个问题,我会非常高兴!
I've got a function that currently grabs all folders and sub-folders to check the ACL's for a small tool I'm building but I'm pulling my hair out trying to figure out how to limit the depth that it can go to. For example you have a folder that goes 4 levels deep but I want to be able to only grab 3 levels of it for ACL's.
Currently I have it coded thusly:
private void StepThroughDirectories(string dir)
{
string[] directories = Directory.GetDirectories(dir);
try
{
foreach (string d in Directory.GetDirectories(dir))
{
if (recCount < (int)Depth)
{
GetACLs(d, new DirectoryInfo(d));
pBar.Value += 1;
//MessageBox.Show("Recursive Level: " + counter.ToString());
recCount++;
StepThroughDirectories(d);
}
else
{
recCount--;
}
}
}
catch (System.Exception e)
{
Console.WriteLine(e.Message);
}
}
Obviously that's not as nice as it was because I've been working on the problem for a little while but if anyone can point me in the right direction to solve this issue I would be very happy!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
首先,避免在外部将
recCount
字段声明为“全局”变量。在递归场景中,沿着递归调用传递状态通常更容易管理。其次,将深度测试移出
foreach
,以消除对文件系统子目录的不必要查询。第三,将实际的处理逻辑放在方法的开头,再次放在子目录处理循环之外。
您的代码将如下所示:
First, avoid declaring the
recCount
field outside as a “global” variable. In recursive scenarios it's usually more manageable to pass state along the recursive calls.Second, move the depth test out of the
foreach
to remove unnecessary querying of the file system for subdirectories.Third, place the actual processing logic at the beginning of your method, again out of the subdirectories processing loop.
Your code would then look like:
一种可能的方法是在方法外部添加一个类字段和一个变量来指示最大深度有多少层。
整数级别;
One possible method, add a class field outside your method and a variable to indicate how many levels deep to go max.
int levels;
当您从 StepThroughDirectories 返回时减少 recCount,但这会更好......
Decrement recCount when you return from StepThroughDirectories, but this would be better...