In my Active Directory (my.domain), I have many groups (UserGrp1, UserGrp2, etc.) which have many users. A user can exist in more than one group. I currently have code that allows me to use the GroupPrincipal class to find a group, and then from there to get all members of that group (see code below). However, what I really need is to find all groups to which a user belongs. For instance, I have a domain user named Joe Test (sAMAccountName=JOETEST) and I need to find all groups to which he belongs. What is the best way to do this?
I can determine if a user belongs to a group (as below) if I loop through all members returned by the GetMembers() method, but this seems inefficient to me and I’d be surprised were there not a more efficient way.
using (PrincipalContext ctx = new PrincipalContext(
ContextType.Domain, "my.domain", "DC=my,DC=domain")) {
if (ctx != null) {
using (GroupPrincipal gp = GroupPrincipal.FindByIdentity(ctx, "UserGrp1")) {
// Get all group members
PrincipalSearchResult<Principal> psr = gp.GetMembers();
foreach (Principal p in psr) {
// other logic
}
}
}
}
Thanks in advance for any help that I receive on this.
Do it by using
UserPrincipal.GetGroups();For a complete code here it is
or for a full AD reference go here.