我目前正在开发使用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
    }
}

我的问题是,什么是创建一个循环来收集信息,如果你这么不知道你的对象子目录的数目最好的方法是什么?

(这可以被应用到任何类型的对象,你不知道对象分层结构)

有帮助吗?

解决方案

使用递归函数,如果你不知道这个层次的深度和需要通过各级穿越了下来。 下面是一个使用深度优先遍历一个例子。

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);
            }
        }
    }
}

可替换地,无需递归,可以通过添加一个队列或堆栈数据结构和存储你看到但还没有尚未访问过的物体做遍历。

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);
            }
        }
    }
}

其他提示

您必须写递归函数为...

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

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

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

您可以使用该递归调用本身对孩子的功能。  退出条件:没有更多的儿童等。

一种选择是使用递归。设置在一个函数然后调用本身foreach循环内的代码时,使下一个目录每次

(子项)

欢迎到递归的精彩世界。你需要接受一个目录作为自变量的函数。鉴于该目录中,它看起来了所有的子目录,并为每一个...自称。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top