简体   繁体   中英

Search Entire Active Directory Forest by username

My organization has active directory forestry consisting of several domain names. I need to write an application to find a user by user id.

        string username = "test_user_id";

        DirectoryEntry entry = new DirectoryEntry("LDAP://one_of_the_domain");
        DirectorySearcher dSearch = new DirectorySearcher(entry);
        dSearch.Filter = "(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + username + "))";
        SearchResult result = dSearch.FindOne();

        if (result != null)
        {
            var email = result.Properties["mail"];
            Console.WriteLine(email[0]);
        }

The sample code above will allow me to search user within one_of_the_domain fine. But is there a way I can find users within entire active directory forest?

Use the Forest class to get the current global catalog, where you then can get a reference to a DirectorySearcher that will search the entire forest.

    var currentForest = Forest.GetCurrentForest();
    var gc = currentForest.FindGlobalCatalog();

    using (var userSearcher = gc.GetDirectorySearcher())
    {
      userSearcher.Filter = 
"(&((&(objectCategory=Person)(objectClass=User)))(samaccountname=" + username + "))";
            SearchResult result = userSearcher.FindOne();

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM