如何使用System.DirectoryServices.ActiveDirectory.Domain类获取域别名

stu*_*bax 3 c# alias active-directory domain-name

我们有一个全名域名,例如long-domainname.com ; 此域名将替换为别名short.可以使用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;
}
Run Code Online (Sandbox Code Playgroud)

此方法返回排序值.但是使用System.DirectoryServices.ActiveDirectory.Domain类及其Name属性,我得到long-domainname.com值.在调试模式下搜索属性,我找不到任何值字段或属性.System.DirectoryServices.ActiveDirectory.Domain上课有可能吗?或者可能有一些其他类的System.DirectoryServices命名空间?如何在不导入外部*.dll的情况下获取域名值?

Met*_*Man 7

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;
    }
Run Code Online (Sandbox Code Playgroud)

  • 我赞成这一点,因为我发现它非常有用.我将DirectoryEntry行更改为:DirectoryEntry rootDSE = new DirectoryEntry(string.Format("LDAP:// {0}/RootDSE",dnsDomainName)); 这样,您就可以在其他(受信任)林中获取域的NETBIOS域名. (2认同)