1

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);
        }
    }

}
Chris Hayes
  • 3,876
  • 7
  • 42
  • 72
  • think i found the answer: http://stackoverflow.com/questions/6354807/how-to-know-if-directoryentry-is-a-user-or-a-group – Chris Hayes Jun 03 '16 at 19:41

1 Answers1

2

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"
    .....
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459