Search code examples
c#authenticationactive-directorywindows-authenticationdirectoryservices

How to list users in all domains running code from a non-domain computer?


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?


Solution

  • You have a couple choices.

    1. If both domains are in the same Forest you could just query the Global Catalog by changing the Domain IP to the Global Catalog IP.

    C# - Searching for users across multiple Active Directory domains

    1. Continue with your hardcoded approach you could create an array of domain IPs. Iterate through the array and call your code for each one in the array.

    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);
                                      }
                                }
                         }
                    }
                }
            }