使用C#检索Active Directory组中的所有用户

Ben*_*Ben 3 c# active-directory active-directory-group

如何检索给定AD组中的用户?

我是否首先使用域,用户名和密码实例化PrincipalContext?

tva*_*son 15

首先,找到该组.然后使用GetMembers()枚举其用户.

using (var context = new PrincipalContext( ContextType.Domain ))
{
     using (var group = GroupPrincipal.FindByIdentity( context, "groupname" ))
     {
           var users = group.GetMembers( true ); // recursively enumerate
           ...
     }
}
Run Code Online (Sandbox Code Playgroud)

请注意,在.NET 4.0中修复了一个错误,它将无法枚举超过1500个组成员.如果您有一个大型组,则需要使用另一种方法,利用System.DirectoryServices中的旧方法.