Reputation: 5162
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?
Upvotes: 1
Views: 4701
Reputation: 5689
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();
}
Upvotes: 5