簡體   English   中英

如何使用 System.DirectoryServices.AccountManagement 在多個域中搜索?

[英]How to search in multiple domains using System.DirectoryServices.AccountManagement?

我有三個或多個域像main.comsub.main.comsub2.main.com和等

我有一個代碼:

using (PrincipalContext ctx = 
    new PrincipalContext(ContextType.Domain, "ADServer", 
    "dc=main,dc=com", ContextOptions.Negotiate))
{
    UserPrincipal u = new UserPrincipal(ctx);
    u.UserPrincipalName = "*" + mask + "*";

    using (PrincipalSearcher ps = new PrincipalSearcher(u))
    {
       PrincipalSearchResult<Principal> results = ps.FindAll();
       List<ADUser> lst = new List<ADUser>();

       foreach (var item in results.Cast<UserPrincipal>().Take(15))
       {
           byte[] sid = new byte[item.Sid.BinaryLength];
           item.Sid.GetBinaryForm(sid, 0);

           ADUser us = new ADUser()
           {
               Sid = sid,
               Account = item.SamAccountName,
               FullName = item.DisplayName
           };

           lst.Add(us);
       }

    }

    return lst;
}

但它只在一個域內搜索: main.com

如何一次搜索所有域中的記錄?

您應該使用 GC 而不是 LDAP。 它沿着整個域森林搜索

var path = "GC://DC=main,DC=com";

try
{
    using (var root = new DirectoryEntry(path, username, password))
    {
        var searchFilter = string.Format("(&(anr={0})(objectCategory=user)(objectClass=user))", mask);
        using (var searcher = new DirectorySearcher(root, searchFilter, new[] { "objectSid", "userPrincipalName" }))
        {
            var results = searcher.FindAll();
            foreach (SearchResult item in results)
            {
                //What ever you do
            }
        }
    }
}

catch (DirectoryServicesCOMException)
{
    // username or password are wrong
}

這是一種從根目錄中查找所有域的方法:

/* Retreiving RootDSE
 */
string ldapBase = "LDAP://DC_DNS_NAME:389/";
string sFromWhere = ldapBase + "rootDSE";
DirectoryEntry root = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");
string configurationNamingContext = root.Properties["configurationNamingContext"][0].ToString();

/* Retreiving the root of all the domains
 */
sFromWhere = ldapBase + configurationNamingContext;
DirectoryEntry deBase = new DirectoryEntry(sFromWhere, "AdminLogin", "PWD");

DirectorySearcher dsLookForDomain = new DirectorySearcher(deBase);
dsLookForDomain.Filter = "(&(objectClass=crossRef)(nETBIOSName=*))";
dsLookForDomain.SearchScope = SearchScope.Subtree;
dsLookForDomain.PropertiesToLoad.Add("nCName");
dsLookForDomain.PropertiesToLoad.Add("dnsRoot");

SearchResultCollection srcDomains = dsLookForDomain.FindAll();

foreach (SearchResult aSRDomain in srcDomains)
{
}

然后foreach域,你可以找你需要的。

要實際使用 System.DirectoryServices.AccountManagement 進行搜索,請指定域如下:

new PrincipalContext(ContextType.Domain, "xyz.mycorp.com:3268", "DC=mycorp,DC=com");

我什么時候需要域名和域容器來創建 PrincipalContext?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM