How to Limit The Depth of a Recursive Sub-Directory Search

前端 未结 3 1431
终归单人心
终归单人心 2021-01-01 01:38

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 ho

相关标签:
3条回答
  • 2021-01-01 01:57

    One possible method, add a class field outside your method and a variable to indicate how many levels deep to go max.

    int levels;

    private void StepThroughDirectories(string dir, int depth)
    {
        levels ++;
        if (levels > depth)
            return;
        string[] directories = Directory.GetDirectories(dir);
        try
        { ...
    
    0 讨论(0)
  • 2021-01-01 01:58

    Decrement recCount when you return from StepThroughDirectories, but this 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);
            }
        } 
    
    0 讨论(0)
  • 2021-01-01 01:59

    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:

    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);
        }
    }
    
    0 讨论(0)
提交回复
热议问题