How to detect if machine is joined to domain?

后端 未结 12 1920
梦毁少年i
梦毁少年i 2020-11-28 08:59

How do I detect whether the machine is joined to an Active Directory domain (versus in Workgroup mode)?

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 09:50

    Here's my methods with exception handling / comments which I developed based on several of the answers in this post.

    1. Gets you the domain the computer is connected to.
    2. Only returns the domain name if the user is actually logged in on a domain account.

      /// 
      /// Returns the domain of the logged in user.  
      /// Therefore, if computer is joined to a domain but user is logged in on local account.  String.Empty will be returned.
      /// Relavant StackOverflow Post: http://stackoverflow.com/questions/926227/how-to-detect-if-machine-is-joined-to-domain-in-c
      /// 
      /// 
      /// Domain name if user is connected to a domain, String.Empty if not.
      static string GetUserDomainName()
      {
          string domain = String.Empty;
          try
          {
              domain = Environment.UserDomainName;
              string machineName = Environment.MachineName;
      
              if (machineName.Equals(domain,StringComparison.OrdinalIgnoreCase))
              {
                  domain = String.Empty;
              }
          }
          catch
          {
              // Handle exception if desired, otherwise returns null
          }
          return domain;
      }
      
      /// 
      /// Returns the Domain which the computer is joined to.  Note: if user is logged in as local account the domain of computer is still returned!
      /// 
      /// 
      /// A string with the domain name if it's joined.  String.Empty if it isn't.
      static string GetComputerDomainName()
      {
          string domain = String.Empty;
          try
          {
              domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name;
          }
          catch
          {
              // Handle exception here if desired.
          }
          return domain;
      }
      

提交回复
热议问题