遍历DirectoryEntry或任何对象层次结构-C# [英] Looping through DirectoryEntry or any object hierarchy - C#

查看:160
本文介绍了遍历DirectoryEntry或任何对象层次结构-C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在开发一个使用System.DirectoryServices命名空间创建DirectoryEntry对象并遍历整个层次结构以收集信息的应用程序.

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.

我不知道层次结构中每个DirectoryEntry对象的子条目数,因此无法通过Children属性为蜘蛛创建N个嵌套循环.

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

这是我的伪代码示例:

//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)

推荐答案

如果您不了解层次结构的深度并且需要遍历所有级别,请使用递归函数. 下面是使用深度优先遍历的示例.

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

或者,无需递归,您可以通过添加Queue或Stack数据结构并存储您已经看到但尚未访问的对象来进行遍历.

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

这篇关于遍历DirectoryEntry或任何对象层次结构-C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆