Mic*_*ern 2 c# directoryservices loops web-crawler hierarchy
我目前正在开发一个使用System.DirectoryServices命名空间创建DirectoryEntry对象的应用程序,并循环遍历整个层次结构以收集信息.
我不知道层次结构中每个DirectoryEntry对象的子条目数,因此我不能通过Children属性为蜘蛛创建N个嵌套循环
这是我的伪代码示例:
//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
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,如果您不知道对象中子目录的数量,创建循环来收集信息的最佳方法是什么?
(这可以应用于您不知道对象层次结构的任何类型的对象)
如果您不知道层次结构的深度并且需要遍历所有级别,请使用递归函数.下面是使用深度优先遍历的示例.
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
或者,在没有递归的情况下,您可以通过添加队列或堆栈数据结构并存储您已看过但尚未访问过的对象来进行遍历.
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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)