Michael Kniskern Michael Kniskern - 23 days ago 9
C# Question

Looping through DirectoryEntry or any object hierarchy - C#

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)

Answer

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.

DirectoryEntry root = new DirectoryEntry(someDN);

DoSomething(root);

function DoSomething(DirectoryEntry de)
{
    // Do some work here against the directory entry

    if (de.Children != null)
    {
        foreach (DirectoryEntry child in de.Children)
        {
            DoSomething(child);
        }
    }
}

Alternatively, without recursion, you can do a traversal by adding a Queue or Stack data structure and storing the objects you've seen but havent visited yet.

Queue<DirectoryEntry> queue = new Queue<DirectoryEntry>();
DirectoryEntry root = new DirectoryEntry(someDN);
queue.Add(root);

while (queue.Any())
{
    DirectoryEntry de = queue.Dequeue();

    // Do some work here against the directory entry

    if (de.Children != null)
    {
        foreach (DirectoryEntry child in de.Children)
        {
            queue.Enqueue(child);
        }
    }
}