2011-11-28 53 views
3

我正在使用C#下面的代碼來輪詢用戶活動目錄搜索LDAP搜索:就像在ActiveDirectory中

DirectoryEntry entry = new DirectoryEntry(ldapPath, userName, password); 

DirectorySearcher Searcher = new DirectorySearcher(entry); 

Searcher.CacheResults = true; 
Searcher.SearchScope = SearchScope.Subtree; 

Searcher.Filter = "(&(&(objectCategory=person)(objectClass=user)) 
    (|(samaccountname=" + userSearch.SamAccountName + "*) 
    (&(GivenName=" + userSearch.FirstName + "*)(SN=" + userSearch.Surname + 
     "*))))"; 

Searcher.PropertiesToLoad.AddRange(new string[] {"DisplayName", "GivenName", 
    "DistinguishedName","Title","manager", 
     "mail", "physicalDeliveryOfficeName", "DirectReports", "Company", 
     "Description", "SAMAccountName"}); 

SearchResultCollection results = Searcher.FindAll(); 

List<ActiveUser> activeUsers = new List<ActiveUser>(); 

我與輸入跑了參數userSearch.FirstName =「喬」和userSearch.LastName = 「bl」,並期待一位用戶「Joe Bloggs」,但這並未出現在結果列表中。如果我使用Windows中的Active Directory用戶和計算機工具中的名稱文本框嘗試此操作,Joe Bloggs將顯示爲列表中的唯一用戶。我正在使用正確的LDAP路徑。我是否使用錯誤的過濾器來複制Windows工具中的功能?顯示名稱上是否有'like'搜索?

任何幫助,將不勝感激。

回答

11

如果你在.NET 3.5或者,你可以使用一個PrincipalSearcher和「查詢通過例如」主要做你的搜索:

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a UserPrincipal 
// and with the first name (GivenName) of "Bruce" 
UserPrincipal qbeUser = new UserPrincipal(ctx); 
qbeUser.GivenName = "Jo*"; 
qbeUser.Surname = "Bl*"; 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    // do whatever here - "found" is of type "Principal" - it could be user, group, computer.....   
} 

如果您還沒有 - 絕對請閱讀MSDN上的文章Managing Directory Security Principals in the .NET Framework 3.5,該文章很好地展示瞭如何充分利用System.DirectoryServices.AccountManagement

+0

中的新功能,非常感謝,我會試試看並通知您。甚至沒有意識到這在3.5中已經改變。仍然卡在過去:) – Sico

+0

@Sico:感覺像一個傳教士告訴大家這個:-)似乎很多人已經「錯過」這個新的命名空間! –

+0

作品一種享受。非常感謝 – Sico