How to limit the depth of a recursive subdirectory search

I have a function that currently captures all folders and subfolders to check the ACL for a small tool that I create, but I am pulling my hair out trying to figure out how to limit the depth, go to. For example, you have a folder with 4 depth levels, but I want to be able to capture only 3 levels for the ACL.

I am currently encoded this way:

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, this is not so pleasant because I have been working on a problem for some time, but if someone can point me in the right direction to solve this problem, I would be very happy!

+6
list c # directory recursion subdirectories
source share
3 answers

First, avoid declaring the recCount field outside as a "global" variable. In recursive scenarios, it is usually more convenient to pass state on recursive calls.

Secondly, move the depth test from foreach to remove unnecessary file system requests for subdirectories.

Third, put the actual processing logic at the beginning of your method, again from the subdirectory processing loop.

Then your code will look like this:

 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); } } 
+18
source share

One possible method, add a class field outside your method and a variable to indicate how many levels a maximum should go through.

int levels;

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

Decrement recCount when you return from StepThroughDirectories, but that would be better ...

  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); } } 
+2
source share

All Articles