简体   繁体   中英

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.

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))
    {
     .....
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM