Search code examples
c#active-directoryactive-directory-group

Retrieve all the users in an Active Directory group using C#


How do I retrieve the users in a given AD group?

Do I start by instantiating a PrincipalContext with a domain, username and password?


Solution

  • First, find the group. Then enumerate its users using GetMembers().

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

    Note that there is a bug, fixed in .NET 4.0, where it will fail to enumerate more than 1500 members of the group. If you have a large group you need to use an alternative method taking advantage of the older methods in System.DirectoryServices.