2012-05-05 26 views
12

我有三個或多個域像main.comsub.main.com,​​和等如何使用System.DirectoryServices.AccountManagement在多個域中進行搜索?

我有一個代碼:

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

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

+1

我不認爲您可以一次搜索多個域。你需要「序列化」你的搜索。 –

+0

你的意思是說我必須知道域名並用循環搜索它們嗎? –

回答

9

這裏是要找到從根一個你的所有域的方式:

/* 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域,你可以看看你需要什麼。

+0

沒有':389'端口在我的情況。 –

+1

你應該在你的域名上找到GC。 – JPBlanc

+0

感謝,也'新的DirectoryEntry(「LDAP:/ /服務器IP/DC =我的域名,DC = COM」,...)'工作正常。 –

20

您應該使用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 
} 
+1

嘿,你去哪裏了? :-)謝謝 –

+0

感謝這工作像一個魅力,比接受的答案更簡單。 – Brandon

+0

Up投票可見度。通過搜索大量資源後的最佳答案 – senthil

相關問題