Search code examples
vb.net.net-2.0active-directorydirectoryservices

How can I get a list of all users that belong to a specific department from Active Directory?


Here's what I'm trying to do:

I want to get a list of all users and groups that belong to a specific department (entered by the user) from Active Directory using VB.Net and DirectoryServices.

Any suggestions?


Solution

  • As long as you're on .NET 2.0, that's probably as good as it gets. What you could do is add the "department" criteria to your search filter - that way, you'd leave it up to AD to do the filtering by department:

    Private Sub GetUsersByDepartment(ByVal department as String)
      Dim deGlobal As DirectoryEntry = New DirectoryEntry(ADPath, ADUser, ADPassword)
      Dim ds As DirectorySearcher = New DirectorySearcher(deGlobal)
    
      ds.Filter = "(&(objectCategory=person)(objectClass=user)(department=" & department & "))"
      ds.SearchScope = SearchScope.Subtree
    
      For Each sr As SearchResult In ds.FindAll
        Dim newDE As DirectoryEntry = New DirectoryEntry(sr.Path)
        If Not newDE Is Nothing Then
              *Do Something*
        End If
      Next
    End Sub
    

    That would certainly help - I hope as a C# programmer, I didn't screw up your VB code!

    The LDAP filter basically allows you to have any number of conditions inside an "anded" bracket (the (&....) around your two conditions - you can easily extend that to three conditions as I did).

    If you have a chance to move up to .NET 3.5, there's a new namespace called System.DirectoryServices.AccountManagement available, which offers much better and more "intuitive" approaches for handling users, groups, computers, and searching.

    Check out the MSDN article Managing Directory Security Principals in the .NET Framework 3.5 to learn more about this.

    What you can do is e.g. "search by example", so you could create a UserPrincipal and set those properties you want to filter on, and then do a search by that object as a "template" almost:

    UserPrincipal user = new UserPrincipal(adPrincipalContext);
    user.Department = "Sales";
    
    PrincipalSearcher pS = new PrincipalSearcher(user);
    
    PrincipalSearchResult<Principal> results = pS.FindAll();
    
    // now you could iterate over the search results and do whatever you need to do
    

    Quite neat indeed ! But only on .NET 3.5, unfortunately.... but wait - that's just a service pack on top of .NET 2, really :-)