我目前正在编写一些代码,通过一些LDAP查询搜索Active Directory。我遇到了Principal
类型的对象,这可能是GroupPrincipal
或UserPrincipal
。但是,如果它是GroupPrincipal
,则它可能包含UserPrincipal
类型的对象。我想将UserPrincipal
类型的所有项目提取到列表中,以便我可以对它们执行其他一些过程。
我想可以使用树木完成,但我不确定如何。
这是我写的一个无效的代码,只有两个节点深度打印名称而不是将它们添加到列表中:
foreach (var principal in group.GetMembers())
{
if (principal is UserPrincipal)
{
var uPrincipal = principal as UserPrincipal;
Console.WriteLine("User: " + uPrincipal.Name);
}
else if (principal is GroupPrincipal)
{
var gPrincipal = principal as GroupPrincipal;
Console.WriteLine("Group: " + gPrincipal.Name);
foreach(var principalito in gPrincipal.GetMembers())
{
if (principalito is UserPrincipal)
{
var uPrincipalito = principalito as UserPrincipal;
Console.WriteLine(">>User: " + uPrincipalito.Name);
}
else if(principalito is GroupPrincipal)
{
var gPrincipalito = principalito as GroupPrincipal;
Console.WriteLine(">>Group: " + gPrincipalito.Name);
}
}
}
}
答案 0 :(得分:0)
试试这个:
public void getAllUserPrinicpals(ref List<UserPrincipal> principals, GroupPrincipal principal)
{
if (principal != null)
{
foreach (Principal princ in principal.GetMembers(true))
{
if (princ is UserPrincipal)
principals.Add((UserPrincipal)princ);
else if (princ is GroupPrincipal)
getAllUserPrinicpals(ref principals, (GroupPrincipal)princ);
}
}
}