How to search in multiple domains using System.DirectoryServices.AccountManagement?

You should use GC instead of LDAP. It searches along whole Domain Forest

var path = "GC://DC=main,DC=com";

try
{
    using (var root = new DirectoryEntry(path, username, password))
    {
        var searchFilter = string.Format("(&(anr={0})(objectCategory=user)(objectClass=user))", mask);
        using (var searcher = new DirectorySearcher(root, searchFilter, new[] { "objectSid", "userPrincipalName" }))
        {
            var results = searcher.FindAll();
            foreach (SearchResult item in results)
            {
                //What ever you do
            }
        }
    }
}

catch (DirectoryServicesCOMException)
{
    // username or password are wrong
}

Here is a way to find all your domains from the root one :

/* Retreiving RootDSE
 */
string ldapBase = "LDAP://DC_DNS_NAME:389/";
string sFromWhere = ldapBase + "rootDSE";
DirectoryEntry root = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");
string configurationNamingContext = root.Properties["configurationNamingContext"][0].ToString();

/* Retreiving the root of all the domains
 */
sFromWhere = ldapBase + configurationNamingContext;
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");

DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase);
dsLookForDomain.Filter = "(&(objectClass=crossRef)(nETBIOSName=*))";
dsLookForDomain.SearchScope = SearchScope.Subtree;
dsLookForDomain.PropertiesToLoad.Add("nCName");
dsLookForDomain.PropertiesToLoad.Add("dnsRoot");

SearchResultCollection srcDomains = dsLookForDomain.FindAll();

foreach (SearchResult aSRDomain in srcDomains)
{
}

Then foreach domain, you can look for what you need.


To actually use System.DirectoryServices.AccountManagement to do the search, specify the domain as such:

new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:3268", "DC=mycorp,DC=com");

From When do I need a Domain Name and a Domain Container to create a PrincipalContext?