title: Identify Current Domain Controller Name
body: <p>I'm attempting to get the current domain controller name via c#.  This code will NOT be running during a logon session. It runs during machine startup so, I can't use the %logonserver% variable because there is no such thing at machine startup.  Searching here I thought the following code would work but it returns the primary domain controller, not the current logon server.  (at startup the 'logon server' might be best referred to as the 'authentication server')</p>
  
  <p>this doesn't work for me (doesn't return machines' current DC, returns Domain's PDC)</p>
  
  <pre><code>    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
          {
              string controller = context.ConnectedServer;
              Console.WriteLine("Domain Controller: " + controller);
          }
  </code></pre>
  
  <p>I have found that the following WMI query gets positive results but, it's slow:</p>
  
  <p>ManagementObjectSearcher searcher = 
                      new ManagementObjectSearcher("root\CIMV2", 
                      "SELECT * FROM Win32_NTDomain"); </p>
  
  <pre><code>            foreach (ManagementObject queryObj in searcher.Get())
              {
                  if (queryObj["DomainControllerName"] != "")
                    Console.WriteLine("DomainControllerName: {0}", queryObj["DomainControllerName"]);
              }
  </code></pre>
  
  <p>Anyone know a better way?  </p>