问题
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:
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.
using (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)
{
using (child)
{
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())
{
using (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);
}
}
}
}
回答2:
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);
}
}
回答3:
You could use a function which recursively calls itself on the children. exit condition: no more children etc..
回答4:
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
回答5:
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.
来源:https://stackoverflow.com/questions/706460/looping-through-directoryentry-or-any-object-hierarchy-c-sharp