I have 2 domains with trusts between them. I have a single Active Directory account in one of these domains that also has permissions in in another domain because of the configured trust. In my application I need to access both domains and list users in them.
My development computer is NOT in the above domains and I cannot add it to these domains. Currently I am using the following code to list users on the domain in which my account was created:
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, "192.168.2.11", “Login1”, “pass1”))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(pc))
{
searchPrincipal.Name = "*";
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
using (PrincipalSearchResult<Principal> principals = searcher.FindAll())
{
foreach (UserPrincipal principal in principals)
{
Console.WriteLine(principal.Name);
}
}
}
}
}
How do I adapt my code to list users from both domains in case I run it on a computer that is not in one of these domains?
You have a couple choices.
C# - Searching for users across multiple Active Directory domains
string[] domains = new string[] {"192.168.2.11","192.168.2.12"};
for(int i = 0; i < domains.Length; i++)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domains[i], “Login1”, “pass1”))
{
using (UserPrincipal searchPrincipal = new UserPrincipal(pc))
{
searchPrincipal.Name = "*";
using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
{
using (PrincipalSearchResult<Principal> principals = searcher.FindAll())
{
foreach (UserPrincipal principal in principals)
{
Console.WriteLine(principal.Name);
}
}
}
}
}
}