Thursday, July 9, 2009

Active Directory in .NET: Recursively find all groups for a user

I had to write a function which returns all the groups (even if they are nested) for a user.
A good thing I discovered the System.DirectoryServices.AccountManagement namespace.

Take a look at the code snippet. I think it's pretty readable.. What do you think?



The GetListOfGroupsRecursively() function tries to find a Principal object by the Username of the ADUser parameter. If the Principal object is found, we call the GetGroups() function and store it's return value in a PrincipalSearchResult. If there are searchresults, we try to get the members for each group by calling the GetMembersForGroup() method. This method recursively searches through all the members of the group looking for Principal objects where the StructuralObjectClass equals "group".

2 comments:

  1. why are you doing everything in .net? is this a requirement?

    ReplyDelete
  2. It is :) Are there other frameworks where LDAP querying is easier?

    ReplyDelete