Search code examples
c#active-directoryprincipalaccount-management

AccountManagement is Principal GroupPrincipal?


How do I take a principal and see if it is a group? or that it has members?

using(var ctx = new PrincipalContext(ContextType.Domain, "some.domain.com", "DC=some,DC=domain,DC=com"))
{
    var group = GroupPrincipal.FindByIdentity(ctx, IdentityType.DistinguishedName, "some long distinguishedname");
    if(group != null)
    {
        var subgroups = group.GetMembers().Where(m => m.[IS A GROUP])
        foreach (var principal in group.GetMembers())
        {
            Console.WriteLine(principal.DistinguishedName);
        }
    }

}

Solution

  • You can "convert" the Principal using the as keyword - if it works, if that object really is a GroupPrincipal, you'll get a valid value, otherwise null:

    var group = GroupPrincipal.FindByIdentity(ctx, 
                                              IdentityType.DistinguishedName, 
                                              "some long dn") as GroupPrincipal;
                                                              ****************** 
    
    if (group != null)
    {
        // now you *know* that it *IS* in fact a "GroupPrincipal"
        .....
    }