vb.netactive-directoryldapactive-directory-groupdirectorysearcher

Querying LDAP in VB.NET. I have the user account, and I want a list of groups the user in in


I know the SAMAccountName, and now want to populate a list of groups with entries that reflect this user's group membership across the whole directory. Here's my start, but I'm stumped:

        Dim path As String = WebConfigurationManager.AppSettings("ldapPath")
        Dim entry As New DirectoryEntry(path)
        Dim search As DirectorySearcher = New DirectorySearcher(entry)
        Dim groupList As StringBuilder = New StringBuilder()
        search.Filter = "(SAMAccountName=" & _thisUser.UserName & ")"
        search.PropertiesToLoad.Add("memberOf")
        'search.SearchScope = SearchScope.Subtree

        For Each res As SearchResult In search.FindAll
        Next  ''Just doing this so I can look at "res" objects in debug

I've no idea how to traverse this. Please, any pointers?


Solution

  • If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace. Read all about it here:

    Basically, you can define a domain context and easily find users and/or groups in AD:

    // set up domain context
    using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
    {
        // find a user
        UserPrincipal user = UserPrincipal.FindByIdentity(ctx, yourSamAccountName);
    
       if(user != null)
       {
            var groups = user.GetGroups();
    
            // iterate over groups or do whatever else you need to do....
       }
    }
    

    The new S.DS.AM makes it really easy to play around with users and groups in AD!