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

Yur*_*lov 13 c# ldap active-directory

我有三个或多个域类似main.com,sub.main.com,sub2.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;
}
Run Code Online (Sandbox Code Playgroud)

但它只在一个域内搜索:main.com.

如何一次搜索所有域中的记录?

Rom*_*eev 24

您应该使用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
}
Run Code Online (Sandbox Code Playgroud)


JPB*_*anc 10

以下是从根目录中查找所有域名的方法:

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

然后是foreach域,你可以找到你需要的东西.