How to search Global Catalog and return a list of UserPrincipals?

4k views Asked by At

I use the following code to search Global Catalog:

public SearchResultCollection SearchGlobalCatalog(string username)
{
    var de = new DirectoryEntry("GC://SERVERNAME", "USERNAME", "PASSWORD");
    var ds = new DirectorySearcher(de);
    ds.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + username + "*))";
    ds.SearchScope = SearchScope.Subtree;                
    var searchResults = ds.FindAll();

    return searchResults;
}

Now, the problem is I don't know how to get a list of UserPrincipal objects from SearchResultCollection. The reason I want to do that is to get access to some user properties that are not available in Global Catalog, like Employee ID.

1

There are 1 answers

9
Cam Bruce On BEST ANSWER

A UserPrincipal is a part of the System.DirectoryServices.AccountManagement namespace.

Use the helper classes in that namespace to get UserPrincipal objects.

Without using a UserPrincipal try something like this:

using (var userBinding = new DirectoryEntry("LDAP://domain.forest.company.com"))
{
    using (DirectorySearcher adSearch = new DirectorySearcher(userBinding))
    {
        adSearch.ReferralChasing = ReferralChasingOption.All;
        adSearch.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + username + "*))";
        adSearch.PropertiesToLoad.Add("employeeID");
        adSearch.PropertiesToLoad.Add("givenname");
        adSearch.PropertiesToLoad.Add("samaccountname");

        var result = adSearch.FindOne();

        var employeeId = result.Properties["employeeID"][0].ToString();
    }
}