如何查询所有组和组成员的Active Directory?

Sin*_*tic 3 .net c# active-directory

我正在查看DirectoryServices名称空间,我正在尝试获取AD中所有组的列表并将它们加载到列表框中.

当我选择一个组时,我希望它填充一个包含管理员名称的文本框以及另一个列表框,其中所有用户都分配给该组.我很难绕过这个过程.有人可以帮帮我吗?

如果我得到一个完整的例子,我相当肯定我会更好地了解更大的图景.TIA

mar*_*c_s 10

如果您在.NET 3.5或更高版本上运行,则可以使用a PrincipalSearcher和"按示例查询"主体进行搜索:

// create your domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);

// define a "query-by-example" principal - here, we search for a GroupPrincipal 
GroupPrincipal qbeGroup = new GroupPrincipal(ctx);

// create your principal searcher passing in the QBE principal    
PrincipalSearcher srch = new PrincipalSearcher(qbeGroup);

// find all matches
foreach(var found in srch.FindAll())
{
     GroupPrincipal foundGroup = found as GroupPrincipal;

     if(foundGroup != null)
     {
        // do whatever you need to do, e.g. put name into a list of strings or something
     }
}
Run Code Online (Sandbox Code Playgroud)

如果您还没有 - 绝对阅读MSDN文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用新功能System.DirectoryServices.AccountManagement

当您拥有一个给定的组时,您可以使用以下方法轻松获取其所有组成员:

// find the group in question (or load it from e.g. your list)
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

// if found....
if (group != null)
{
   // iterate over members
   foreach (Principal p in group.GetMembers())
   {
      Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
      // do whatever you need to do to those members
   }
}
Run Code Online (Sandbox Code Playgroud)