Search code examples
c#asp.netldapdirectorysearcher

Get List of all users with the same physicalDeliveryOfficeName from AD in Visual C#


I'd like to search my active directory for all users that belong to a particular physicalDeliveryOfficeName (LDAP) and store them into an array of type SearchResult. Can I do this with a DirectorySearcher filter? Or is there a better approach?

I'm using asp.net, visual c#. Thanks!


Solution

  • Using the DirectorySeacher class, your query could be

    (&(objectClass=user)(physicalDeliveryOfficeName=Kalkutta))
    

    where objectClass=user to get only user entries and physicalDeliveryOfficeName=Kalkutta is your query for an office.

    DirectoryEntry entry = new DirectoryEntry("LDAP://...");           
    DirectorySearcher search = new DirectorySearcher(entry)
        {
             SearchScope = SearchScope.Subtree,
             Filter = "(&(objectClass=user)(physicalDeliveryOfficeName=Kalkutta))"
        };
    search.PropertiesToLoad.Add("cn");
    SearchResultCollection result = search.FindAll();
    foreach (SearchResult r in result)
         Response.Write(r.Properties["cn"][0]);