鉴于具有大量成员的特定组,我想在组内查询以查找具有DisplayName匹配的成员。
下面的代码是我想要完成的非功能性示例。请注意,我不想先加载整个列表然后应用'where',我已经可以这样做了,因为组很大,所以它很慢。
public static List<Principal> FindUsersOfGroup(string groupName, string displayNameQuery)
{
using (var context = new PrincipalContext(ContextType.Machine, Environment.MachineName))
{
var search = new GroupPrincipal(context);
search.SamAccountName = groupName;
// This where doesn't work, but is what I'm looking for.
search.Members.Where(m => m.DisplayName == displayNameQuery + "*");
using (var ps = new PrincipalSearcher(search))
{
// Want to get all members that match the query AND belong to the group.
return ps.FindAll().ToList();
}
}
}
此外,上下文是我真实代码中的Domain,我故意替换它。
答案 0 :(得分:1)
您可以使用DirectorySearcher类执行此类操作:
using (DirectoryEntry entry = new DirectoryEntry("LDAP://" + Environment.UserDomainName))
{
using (DirectorySearcher searcher = new DirectorySearcher(
entry,
string.Format(
"(&(objectCategory=person)(objectClass=user)(displayName={0}*)(memberof={1}))",
displayNameQuery,
groupName)))
{
searcher.PropertiesToLoad.Add("samAccountname"); //You can specify which properties you want to load. If you don't specify properties, by default you will get a lot of properties. Loading specific properties is better in terms of performance
using (var results = searcher.FindAll())
{
foreach (var result in results.Cast<SearchResult>())
{
//Do something with result
var properties = result.Properties;
//Example
var samAccountName = properties["samAccountName"][0];
//...
}
}
}
}
在这种情况下, groupName
是该组的可分辨名称(例如CN = Administrators,CN = Builtin,DC = dnb,DC = lab)