我正在使用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<ActiveUser> activeUsers = new List<ActiveUser>();
我使用输入参数userSearch.FirstName =“jo”和userSearch.LastName =“bl”运行它,并期待一个用户“Joe Bloggs”,但这没有出现在结果列表中。如果我使用Windows中的Active Directory用户和计算机工具中的名称文本框尝试此操作,则Joe Bloggs将显示为列表中的唯一用户。我正在使用正确的LDAP路径。我使用错误的过滤器来复制Windows工具中的功能吗?显示名称上是否有“喜欢”搜索?
任何帮助都将不胜感激。
答案 0 :(得分:13)
如果您使用的是.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