You would have to do the search recursively expanding every subgroup that is a member of another group.
However, there is a lot easier method using the GroupPrincipal
class of the System.DirectoryServices.AccountManagement namespace.
GroupPrincipal
has a method GetMembers
which allows you to retrieve all members of a group recursively. All you have to do is specify true
as the only parameter to GetMembers.
The following example is copied from MSDN:
PrincipalContext ctx = new PrincipalContext(ContextType.Domain,
"fabrikam.com",
"DC=fabrikam,DC=com",
"administrator",
"SecretPwd123");
GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx,
IdentityType.Name,
"Domain Admins");
if (grp != null)
{
foreach (Principal p in grp.GetMembers(recursive: true))
{
Console.WriteLine(p.Name);
}
grp.Dispose();
}
ctx.Dispose();