喜欢在ActiveDirectory中搜索

我在C#中使用以下代码搜索LDAP以轮询用户的活动目录:

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 activeUsers = new List(); 

我使用输入参数userSearch.FirstName =“jo”和userSearch.LastName =“bl”运行它,并且期望一个用户“Joe Bloggs”,但这没有出现在结果列表中。 如果我使用Windows中的Active Directory用户和计算机工具中的名称文本框尝试此操作,则Joe Bloggs将显示为列表中的唯一用户。 我正在使用正确的LDAP路径。 我使用错误的filter来复制Windows工具中的function吗? 显示名称上有“喜欢”搜索吗?

任何帮助,将不胜感激。

如果您使用的是.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文章.NET Framework 3.5中的管理目录安全主体,它很好地展示了如何充分利用System.DirectoryServices.AccountManagement中的新function