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

Ben Aston picture Ben Aston · Jan 20, 2010 · Viewed 12k times · Source

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

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

Answer

tvanfosson picture tvanfosson · Jan 20, 2010

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.