如何用System.DirectoryServices.AccountManagement查找Pager字段含指定字符串的AD用户
在C#中使用System.DirectoryServices.AccountManagement实现AD用户Pager字段模糊搜索
我之前也碰到过类似的困扰——直接用System.DirectoryServices.AccountManagement的LINQ查询做模糊匹配确实有点受限,因为它对LDAP查询的支持不够灵活。不过咱们可以换个思路,直接调用底层的DirectorySearcher来构建LDAP过滤条件,这样就能轻松实现Pager字段的包含式搜索了。
核心思路
LDAP本身支持通配符*来实现模糊匹配,我们可以利用这一点,构建一个精准的LDAP过滤字符串,直接搜索AD中Pager字段包含指定内容的用户。
完整代码示例
using System; using System.DirectoryServices; using System.DirectoryServices.AccountManagement; class Program { static void Main() { // 1. 建立AD上下文连接 var domainContext = new PrincipalContext(ContextType.Domain, "yourDomainName"); // 2. 构建LDAP过滤条件:匹配Pager字段包含" 1234 "的用户 // 注意:LDAP中*是通配符,代表任意长度的任意字符(包括空) string ldapFilter = "(&(objectCategory=person)(objectClass=user)(pager=* 1234 *))"; // 3. 创建DirectorySearcher并执行搜索 using var searcher = new DirectorySearcher(domainContext.UnderlyingObject, ldapFilter); // 可选:指定要返回的属性,提升查询效率(如果不需要所有属性的话) searcher.PropertiesToLoad.Add("samaccountname"); searcher.PropertiesToLoad.Add("pager"); searcher.PropertiesToLoad.Add("displayname"); // 4. 遍历搜索结果 foreach (SearchResult result in searcher.FindAll()) { // 方式一:直接提取所需属性(更高效) string samAccountName = result.Properties["samaccountname"][0].ToString(); string pagerValue = result.Properties["pager"][0].ToString(); string displayName = result.Properties["displayname"][0].ToString(); Console.WriteLine($"用户: {displayName} ({samAccountName}) | Pager: {pagerValue}"); // 方式二:转换为UserPrincipal对象(方便获取更多用户属性) // using var userPrincipal = UserPrincipal.FindByIdentity( // domainContext, // IdentityType.DistinguishedName, // result.Properties["distinguishedname"][0].ToString() // ); // if (userPrincipal != null) // { // Console.WriteLine($"用户: {userPrincipal.DisplayName} | Pager: {userPrincipal.Pager}"); // } } } }
关键细节说明
- LDAP过滤条件:
(&(objectCategory=person)(objectClass=user)(pager=* 1234 *))中,pager=* 1234 *表示匹配Pager字段中任意位置包含" 1234 "(前后带空格)的用户。如果不需要空格,改成pager=*1234*即可。 - 性能优化:通过
PropertiesToLoad指定需要返回的属性,避免查询不必要的AD属性,提升搜索速度。 - 权限注意:运行代码的账户需要拥有读取AD用户属性的权限,否则会抛出权限不足的异常。
- 为什么不用UserPrincipal的LINQ查询?:
AccountManagement的LINQ Provider对LDAP的支持有限,虽然Contains方法看似能实现模糊搜索,但实际底层转换可能因为AD配置或库的限制无法生效,直接使用DirectorySearcher是更可靠的方案。
内容的提问来源于stack exchange,提问作者Eric Brown - Cal
相关产品推荐
相关产品推荐

