System.DirectoryServices.AccountManagement.PrincipalCollection - how to check if the primary user or 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, I want to know (based on a collection of members) whose members are users and which are groups. Depending on what type they are, I need to eliminate additional logic.

+6
source share
1 answer

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 a user! { ...... } else { GroupPrincipal group = (principal as GroupPrincipal); if(group != null) // it a group { .... } } } 

Basically, you just apply the type you need using the as keyword - if null , then the listing failed, otherwise it succeeded.

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

 foreach (var principal in gp.Members) { Type type = principal.GetType(); if(type == typeof(UserPrincipal)) { ... } else if(type == typeof(GroupPrincipal)) { ..... } } 
+12
source

Source: https://habr.com/ru/post/901236/


All Articles