如何限制递归子目录搜索的深度

我有一个function,目前抓住所有文件夹和子文件夹,检查ACL是否正在建立一个小工具,但我正在试着弄清楚如何限制它可以达到的深度。 例如,你有一个4级深度的文件夹,但我希望只能为ACL获取3个级别的文件夹。

目前我有它编码:

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

一种可能的方法是在方法外添加一个类字段,并在变量中添加一个变量来指示最大深度。

int水平;

 private void StepThroughDirectories(string dir, int depth) { levels ++; if (levels > depth) return; string[] directories = Directory.GetDirectories(dir); try { ... 

从StepThroughDirectories返回时减少recCount,但这会更好……

  private void StepThroughDirectories(string dir, int depth) { if (depth < 0) return; string[] directories = Directory.GetDirectories(dir); try { foreach (string d in Directory.GetDirectories(dir)) { // your code here Console.WriteLine("{0}", d); StepThroughDirectories(d, depth-1); } } catch (System.Exception e) { Console.WriteLine(e.Message); } }