2012-12-11 41 views
1

我們有一個具有全名的域,例如long-domainname.com;此域名替換爲別名。此別名可使用netapi32.dll被檢索,這樣的:如何使用System.DirectoryServices.ActiveDirectory.Domain獲取域別名類

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

// Returns the domain name the computer is joined to, or "" if not joined. 
public static string GetJoinedDomain() 
{ 
    int result = 0; 
    string domain = null; 
    IntPtr pDomain = IntPtr.Zero; 
    NetJoinStatus status = NetJoinStatus.NetSetupUnknownStatus; 
    try 
    { 
     result = NetGetJoinInformation(null, out pDomain, out status); 
     if (result == ErrorSuccess && 
      status == NetJoinStatus.NetSetupDomainName) 
     { 
      domain = Marshal.PtrToStringAuto(pDomain); 
     } 
    } 
    finally 
    { 
     if (pDomain != IntPtr.Zero) NetApiBufferFree(pDomain); 
    } 
    if (domain == null) domain = ""; 
    return domain; 
} 

此方法返回排序值。但使用System.DirectoryServices.ActiveDirectory.Domain類和它的Name屬性,我得到long-domainname.com值。在調試模式下搜索屬性時,找不到任何值字段或屬性。 System.DirectoryServices.ActiveDirectory.Domain課程有可能嗎?或者可能與其他類System.DirectoryServices命名空間是可能的?如何獲得域名值而不導入外部* .dll?

回答

4
private string GetNetbiosDomainName(string dnsDomainName) 
    { 
     string netbiosDomainName = string.Empty; 

     DirectoryEntry rootDSE = new DirectoryEntry("LDAP://RootDSE"); 

     string configurationNamingContext = rootDSE.Properties["configurationNamingContext"][0].ToString(); 

     DirectoryEntry searchRoot = new DirectoryEntry("LDAP://cn=Partitions," + configurationNamingContext); 

     DirectorySearcher searcher = new DirectorySearcher(searchRoot); 
     searcher.SearchScope = SearchScope.OneLevel; 
     searcher.PropertiesToLoad.Add("netbiosname"); 
     searcher.Filter = string.Format("(&(objectcategory=Crossref)(dnsRoot={0})(netBIOSName=*))", dnsDomainName); 

     SearchResult result = searcher.FindOne(); 

     if (result != null) 
     { 
      netbiosDomainName = result.Properties["netbiosname"][0].ToString(); 
     } 

     return netbiosDomainName; 
    } 
+2

我提高了這一點,因爲我覺得它非常有用。我將DirectoryEntry行更改爲:DirectoryEntry rootDSE = new DirectoryEntry(string.Format(「LDAP:// {0}/RootDSE」,dnsDomainName));這樣您就可以獲得其他(可信任)森林中域的NETBIOS域名。 – Daro

+0

謝謝達羅..很高興信息是有用的..新年快樂... – MethodMan

+0

我欠你謝謝... – Daro