2009-05-29 57 views

回答

24

你可以的PInvoke到Win32 API中的諸如NetGetDcName這將返回一個空/空字符串的非加入域的機器。

更好的是NetGetJoinInformation它會明確告訴你機器是否在工作組或域中未被連接。

使用NetGetJoinInformation我放在一起這一點,這爲我工作:

public class Test 
{ 
    public static bool IsInDomain() 
    { 
     Win32.NetJoinStatus status = Win32.NetJoinStatus.NetSetupUnknownStatus; 
     IntPtr pDomain = IntPtr.Zero; 
     int result = Win32.NetGetJoinInformation(null, out pDomain, out status); 
     if (pDomain != IntPtr.Zero) 
     { 
      Win32.NetApiBufferFree(pDomain); 
     } 
     if (result == Win32.ErrorSuccess) 
     { 
      return status == Win32.NetJoinStatus.NetSetupDomainName; 
     } 
     else 
     { 
      throw new Exception("Domain Info Get Failed", new Win32Exception()); 
     } 
    } 
} 

internal class Win32 
{ 
    public const int ErrorSuccess = 0; 

    [DllImport("Netapi32.dll", CharSet=CharSet.Unicode, SetLastError=true)] 
    public static extern int NetGetJoinInformation(string server, out IntPtr domain, out NetJoinStatus status); 

    [DllImport("Netapi32.dll")] 
    public static extern int NetApiBufferFree(IntPtr Buffer); 

    public enum NetJoinStatus 
    { 
     NetSetupUnknownStatus = 0, 
     NetSetupUnjoined, 
     NetSetupWorkgroupName, 
     NetSetupDomainName 
    } 

} 
6
ManagementObject cs; 
     using(cs = new ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'")) 
     { 
      cs.Get(); 
      Console.WriteLine("{0}",cs["domain"].ToString()); 
     } 

這應該讓你獲得域名。我相信如果你是工作組的一部分而不是域,它將是空的或空的。

確保引用System.Management

+0

如果不在域中,它將返回「WORKGROUP」。這將起作用(除非你在名爲「WORKGROUP」的域中!),但在選擇它作爲正確答案之前,我會稍等一下,看看是否有非基於WMI的方法。 – DSO 2009-05-29 14:38:04

+0

謝謝你讓我知道。我只有我的工作機器進行測試,並且無法將其完全從域中刪除以進行測試。 – Stephan 2009-05-29 14:41:24

+2

第二個想法我不認爲這會奏效。事實證明,我的測試框的工作組名稱實際上是WORKGROUP。我認爲它返回工作組名稱,而不是一個固定的值,從API的角度來看這更有意義,但它意味着你不能用它來確定它的域是否加入。 – DSO 2009-05-29 16:31:00

3

的環境變量可以爲你工作。

Environment.UserDomainName 

MSDN Link瞭解更多詳情。

Environment.GetEnvironmentVariable("USERDNSDOMAIN") 

我不確定此環境變量是否存在,而不在域中。

糾正我,如果我錯了的Windows管理員怪才 - 我相信電腦可以在幾個領域,因此它可能是更重要的是要知道你是不是它任何是什麼域,如果有的話,域。

85

如果您不必這樣做,就別傻瓜了。

參考的System.DirectoryServices,然後調用:

System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain() 

拋出ActiveDirectoryObjectNotFoundException如果機器未加入域。 返回的域對象包含您正在查找的Name屬性。

4

只是想砸搶的代碼在VB:

Public Class Test 
    Public Function IsInDomain() As Boolean 
     Try 
      Dim status As Win32.NetJoinStatus = Win32.NetJoinStatus.NetSetupUnknownStatus 
      Dim pDomain As IntPtr = IntPtr.Zero 
      Dim result As Integer = Win32.NetGetJoinInformation(Nothing, pDomain, status) 

      If (pDomain <> IntPtr.Zero) Then 
       Win32.NetApiBufferFree(pDomain) 
      End If 

      If (result = Win32.ErrorSuccess) Then 
       If (status = Win32.NetJoinStatus.NetSetupDomainName) Then 
        Return True 
       Else 
        Return False 
       End If 
      Else 
       Throw New Exception("Domain Info Get Failed") 
      End If 
     Catch ex As Exception 
      Return False 
     End Try 
    End Function 
End Class 
Public Class Win32 
    Public Const ErrorSuccess As Integer = 0 
    Declare Auto Function NetGetJoinInformation Lib "Netapi32.dll" (ByVal server As String, ByRef IntPtr As IntPtr, ByRef status As NetJoinStatus) As Integer 
    Declare Auto Function NetApiBufferFree Lib "Netapi32.dll" (ByVal Buffer As IntPtr) As Integer 
    Public Enum NetJoinStatus 
     NetSetupUnknownStatus = 0 
     NetSetupUnjoined 
     NetSetupWorkgroupName 
     NetSetupDomainName 
    End Enum 
End Class 

以及史蒂芬代碼在這裏:

Dim cs As System.Management.ManagementObject 
    Try 
     cs = New System.Management.ManagementObject("Win32_ComputerSystem.Name='" + System.Environment.MachineName + "'") 
     cs.Get() 
     dim myDomain as string = = cs("domain").ToString 
    Catch ex As Exception 
    End Try 


我認爲,只有第二個代碼將讓你知道什麼即使當前用戶不是域成員,域也會加入該域。

2

這裏是我基於本文中的幾個答案開發的異常處理/註釋方法。

  1. 獲取您計算機連接到的域。
  2. 僅當用戶實際登錄到域帳戶時才返回域名。

    /// <summary> 
    /// 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 
    /// </summary> 
    /// <seealso cref="GetComputerDomainName"/> 
    /// <returns>Domain name if user is connected to a domain, String.Empty if not.</returns> 
    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; 
    } 
    
    /// <summary> 
    /// 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! 
    /// </summary> 
    /// <seealso cref="GetUserDomainName"/> 
    /// <returns>A string with the domain name if it's joined. String.Empty if it isn't.</returns> 
    static string GetComputerDomainName() 
    { 
        string domain = String.Empty; 
        try 
        { 
         domain = System.DirectoryServices.ActiveDirectory.Domain.GetComputerDomain().Name; 
        } 
        catch 
        { 
         // Handle exception here if desired. 
        } 
        return domain; 
    } 
    
1

您可能需要使用DomainRole兩個WMI領域嘗試。 0和2的值分別顯示獨立工作站和獨立服務器。

我們正在使用此爲夏配置我們的網絡審計軟件,所以我在那兒剽竊此方法...

/// <summary> 
/// Determines whether the local machine is a member of a domain. 
/// </summary> 
/// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns> 
/// <remarks>http://msdn.microsoft.com/en-gb/library/windows/desktop/aa394102(v=vs.85).aspx</remarks> 
public bool IsDomainMember() 
{ 
    ManagementObject ComputerSystem; 
    using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName))) 
    { 
     ComputerSystem.Get(); 
     UInt16 DomainRole = (UInt16)ComputerSystem["DomainRole"]; 
     return (DomainRole != 0 & DomainRole != 2); 
    } 
} 
3

您可以檢查的Win32_ComputerSystem WMI類的PartOfDomain財產。 的MSDN說:

PartOfDomain

數據類型:布爾

訪問類型:只讀

如果真,計算機是域的一部分。如果該值爲NULL,則該計算機不在域中或狀態未知。如果 從域中脫離計算機,則該值將變爲false。

/// <summary> 
/// Determines whether the local machine is a member of a domain. 
/// </summary> 
/// <returns>A boolean value that indicated whether the local machine is a member of a domain.</returns> 
/// <remarks>http://msdn.microsoft.com/en-us/library/windows/desktop/aa394102%28v=vs.85%29.aspx</remarks> 
public bool IsDomainMember() 
{ 
    ManagementObject ComputerSystem; 
    using (ComputerSystem = new ManagementObject(String.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName))) 
    { 
     ComputerSystem.Get(); 
     object Result = ComputerSystem["PartOfDomain"]; 
     return (Result != null && (bool)Result); 
    } 
} 
9

也可以通過使用system.net

string domain = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().DomainName 

如果域字符串是空的機器未綁定調用。

1

如果性能問題,使用GetComputerNameEx功能:

bool IsComputerInDomain() 
    { 
     uint domainNameCapacity = 512; 
     var domainName = new StringBuilder((int)domainNameCapacity); 
     GetComputerNameEx(COMPUTER_NAME_FORMAT.ComputerNameDnsDomain, domainName, ref domainNameCapacity); 
     return domainName.Length > 0; 
    } 

    [DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)] 
    static extern bool GetComputerNameEx(
     COMPUTER_NAME_FORMAT NameType, 
     StringBuilder lpBuffer, 
     ref uint lpnSize); 

    enum COMPUTER_NAME_FORMAT 
    { 
     ComputerNameNetBIOS, 
     ComputerNameDnsHostname, 
     ComputerNameDnsDomain, 
     ComputerNameDnsFullyQualified, 
     ComputerNamePhysicalNetBIOS, 
     ComputerNamePhysicalDnsHostname, 
     ComputerNamePhysicalDnsDomain, 
     ComputerNamePhysicalDnsFullyQualified 
    } 
1

您可以查看使用WMI

private bool PartOfDomain() 
{ 
    ManagementObject manObject = new ManagementObject(string.Format("Win32_ComputerSystem.Name='{0}'", Environment.MachineName)); 
    return (bool)manObject["PartOfDomain"]; 
}