views:

3184

answers:

5

I am currently developing an application that use the System.DirectoryServices namespace to create a DirectoryEntry object and loop through the entire hierarchy to collect information.

I do not know number of child entries for each DirectoryEntry object in the hierarchy, so I can not create a N number of nested loops to spiders through the Children property

Here is my pseudo code example:

//root directory
DirectoryEntry root = new DirectoryEntry(path);

if(DirectoryEntry.Childern != null)
{
    foreach(DirectoryEntry child in root.Children)
    {
        //loop through each Children property unitl I reach the last sub directory
    }
}

My question is, what is the best way to create a loop to collect information if you so not know the number of sub directories in your object?

(This can be applied to any type of object that you do not know the object hierarchy)

+1  A: 

You could use a function which recursively calls itself on the children. exit condition: no more children etc..

Indeera
+4  A: 

Use a recursive function if you don't know the depth of the hierarchy and need to traverse down through all levels. Below is an example using depth-first traversal.

var root = new DirectoryEntry(someDN);

DoSomething(root);

function DoSomething(DirectoryEntry de)
{
    // Do some work here against the directory entry
    if (de.Children != null)
    {
        foreach (var child in de.Children)
        {
            DoSomething(child);
        }
    }
}
David Archer
This, btw, is a good example of where recursion is actually a good way to handle a problem. Because the file system itself imposes depth limitations, you shouldn't blow the stack. You have to be careful, however, in case there is a loop in the tree do to links...
jeffamaphone
@jeffmaphone: DirectoryEntry actually is going to be pointing at an LDAP server, not the file system. I'm not sure about the LDAP depth limits but if there are loops, the easiest way to handle it is to record the GUID of each entry you visit and stop recursing if you visit the same entry twice.
David Archer
+1  A: 

One option is to use Recursion. Set that code up in a function that then calls itself inside the foreach loop, passing the next directory (child item) each time

John
+1  A: 

Welcome to the wonderful world of recursion. You need a function that accepts a Directory as an argument. Given that directory, it looks up all of the child directories and for each one... calls itself.

Joel Coehoorn
+1  A: 

You have to write recursive function as...

DirectoryEntry root = new DirectoryEntry(path);
DoForEveryNode(root);

void DoForEveryNode(DirectoryEntry node)
{
    // do something..

    foreach(DirectoryEntry child in node.Children)
    {
        DoForEveryNode(child);
    }
}
Akash Kava