2012-05-05 13 views
12

私はmain.comsub.main.com、​​となどSystem.DirectoryServices.AccountManagementを使用して複数のドメインを検索するにはどうすればよいですか?

などの3つの以上のドメインを持っている私は、コードがあります。

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

がルート1からすべてのドメインを見つけるための方法です:

/* 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 = my-domain、DC = com」、...) 'もうまくいきました。 –

20

LDAPの代わりにGCを使用する必要があります。これは、実際に検索を行うためにSystem.DirectoryServices.AccountManagementを使用するには、ドメイン全体の森

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

ねえ、どこにいましたか? :-) thanks –

+0

ありがとう、これは魅力のように動作し、受け入れられた答えよりも簡単です。 – Brandon

+0

アップは投票のために投票しました。多くのリソースを通じて検索した後のベストアンサー – senthil

関連する問題