我有一个功能,当前可以抓取所有文件夹和子文件夹来检查我正在构建的小工具的 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);
}
}
显然,这并不像以前那么好,因为我已经研究这个问题一段时间了,但如果有人能指出我解决这个问题的正确方向,我会非常高兴!
首先,避免声明recCount
外部字段作为“全局”变量。在递归场景中,沿着递归调用传递状态通常更容易管理。
其次,将深度测试移出foreach
删除文件系统中不必要的子目录查询。
第三,将实际的处理逻辑放在方法的开头,再次放在子目录处理循环之外。
您的代码将如下所示:
void StepThroughDirectories(string dir)
{
StepThroughDirectories(dir, 0)
}
void StepThroughDirectories(string dir, int currentDepth)
{
// process 'dir'
...
// process subdirectories
if (currentDepth < MaximumDepth)
{
foreach (string subdir in Directory.GetDirectories(dir))
StepThroughDirectories(subdir, currentDepth + 1);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)