How do I find out which computer is the domain controller in Windows programmatically?

前端 未结 7 1009
星月不相逢
星月不相逢 2021-01-30 08:17

I am looking for a way to determine what the Name/IP Address of the domain controller is for a given domain that a client computer is connected to.

At our company we hav

7条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-30 08:30

    In C#/.NET 3.5 you could write a little program to do:

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    {
        string controller = context.ConnectedServer;
        Console.WriteLine( "Domain Controller:" + controller );
    } 
    

    This will list all the users in the current domain:

    using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
    {
        using (UserPrincipal searchPrincipal = new UserPrincipal(context))
        {
           using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
           {
               foreach (UserPrincipal principal in searcher.FindAll())
               {
                   Console.WriteLine( principal.SamAccountName);
               }
           }
        }
    }
    

提交回复
热议问题