Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.DirectoryServices.AccountManagement.PrincipalCollection - how to check if principal is a user or a group?

Consider the following code:

GroupPrincipal gp = ... // gets a reference to a group

foreach (var principal in gp.Members)
 {
       // How can I determine if principle is a user or a group?         
 }

Basically what I want to know is (based on the members collection) which members are users and which are groups. Depending on what type they are, I need to fire off additional logic.

like image 901
JL. Avatar asked Nov 10 '11 19:11

JL.


1 Answers

Easy:

foreach (var principal in gp.Members)
{
       // How can I determine if principle is a user or a group?         
    UserPrincipal user = (principal as UserPrincipal);

    if(user != null)   // it's a user!
    {
     ......
    }
    else
    {
        GroupPrincipal group = (principal as GroupPrincipal);

        if(group != null)  // it's a group 
        {
           ....
        }
    }
}

Basically, you just cast to a type you're interested in using the as keyword - if the value is null then the cast failed - otherwise it succeeded.

Of course, another option would be to get the type and inspect it:

foreach (var principal in gp.Members)
{
    Type type = principal.GetType();

    if(type == typeof(UserPrincipal))
    {
      ...
    }
    else if(type == typeof(GroupPrincipal))
    {
     .....
    }
}
like image 126
marc_s Avatar answered Sep 29 '22 08:09

marc_s