views:

445

answers:

2

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

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

+2  A: 

Check out this article Managing Directory Security Principals in the .NET Framework 3.5 for a great overview of what you can do with System.DirectoryServices.AccountManagement in .NET 3.5.

As for retrieving the members of a group, you do this:

// build the principal context - use the NetBIOS domain name
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAIN");

// get the group you're interested in
GroupPrincipal group = GroupPrincipal.FindByIdentity("cn=YourGroupname");

// iterate over its members
foreach(Principal p in group.Members)
{
    // do whatever you need to do to its members here            
}

Hope this helps!

marc_s
+4  A: 

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.

tvanfosson
Chosen as answer because of depth of knowledge re enumeration bug, but all answers were great.
Ben Aston