我们有一个全名的域,例如 long-domainname.com ;该域名被替换为别名 。可以使用 netapi32.dll 检索此别名,如下所示:

[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 值。在 Debug模式下搜索属性,我找不到任何 值字段或属性。 System.DirectoryServices.ActiveDirectory.Domain 类可以吗?或者可能有一些其他类的 System.DirectoryServices 命名空间?如何在不导入外部*.dll 的情况下获取 域名值?

最佳答案

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;
    }

关于c# - 如何使用 System.DirectoryServices.ActiveDirectory.Domain 类获取域别名,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/13814423/

10-14 13:50