c# - Active Directory OU 树到 jqTree

标签 c# json active-directory jqtree

我需要创建一个有效的 jqTree来自 Active Directory OU 的 JSON 结构。我正在为此使用递归方法 (InfoNode) 进行测试,但我无法获取它。

生成的 json 进入字符串 json。要处理的第一个节点是具有默认域根的 DirectoryEntry 父节点。递归方法(InfoNode)得到 当前子节点,按“OU”过滤并创建 JSON 属性“label”和“path”。 Before 检查此节点是否有更多子节点写入当前 JSON 项目的末尾。最后,如果有更多的 child ,再次运行方法(InfoNode):

public static DirectoryEntry root = new DirectoryEntry("LDAP://RootDSE");
public string dom = (string)root.Properties["defaultNamingContext"].Value;

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

void InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');

    if (arr[0] == "OU")
    {
        json += "'children':[{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (nodo.Children == null)
        {
            json += "}]";
        }
        else
        {
            json += ",";
        }              
    }

    if (node.Children != null)
    {
        foreach (DirectoryEntry child in node.Children)
        {
            InfoNode(child);
        }
    }
}

最佳答案

您应该提供有关代码失败原因的更多详细信息。

我会试一试 :-)

您可以尝试修改您的代码,如下所示。 不是最优的(在拆分之前使用 startswith,更多的 string.Format,在递归调用方法之前使用 startswith 测试 child 会更好),但我想它应该可以工作。

当您在树中前进时,您可能需要从 ldap 源加载子项。

public string json = "";

public Form1()
{
    InitializeComponent();
    DirectoryEntry parent = new DirectoryEntry("LDAP://" + dom);
    json = InfoNode(parent);
    System.IO.File.WriteAllText(@"json.txt", json);
}

public string InfoNode(DirectoryEntry node)
{
    string[] arr = node.Name.Split('=');
    var result = string.Empty;

    if (arr[0].Equals("ou",StringComparison.InvariantCultureIgnoreCase))
    {
        result = "'{'label':'" + arr[1] + "','path':'" + node.Path + "'";

        if (node.Children.Cast<DirectoryEntry>().Any())
        {
            result += String.Format(", children:[{0}]",
                                    String.Join(",\n ",
                                                node.Children.Cast<DirectoryEntry>()
                                                    .Select(InfoNode).Where(s=>!string.IsNullOrEmpty(s))
                                                    .ToArray()));
        }
        result += "}";
    }
    return result;
}

关于c# - Active Directory OU 树到 jqTree,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13700814/

相关文章:

c# - 从 Active Directory 中读取已删除的用户

c# - byte[] 到十六进制字符串

c# - Xamarin。 X509Certificate 和 ClientBase

arrays - 复杂对象的 json 数组在发布时始终为 null

python - 使用 OFFSET 在 Python 中迭代 JSON

c# - 使用不在域上的 DirectoryEntry,设置用户密码永不过期

c# - new Version(AssemblyFileVersionAttribute.Version) 总是会成功吗?

c# - 使用 DataContract 从 List<> 派生的类的序列化

python - 逐行读取文件,并获取以某个单词开头的行?

c# - DirectoryEntry.Invoke ChangePassword 上的 Active Directory 访问被拒绝异常