如何搜索显示名称中包含字母(或少数字母)的用户

问题描述 投票:1回答:2

我会试着更好地解释自己。我正在使用C#为自己构建一个迷你程序。我想在我的活动目录中搜索用户,但我想搜索没有完整显示名称的用户。让我解释一下自己。例如,我的显示名称可以是:“David Holonka \ Jeramy”。有没有办法搜索字母“lonka”,它会找到所有在显示名称中包含这些字母组合的用户?

我目前的代码:

using (var pc = new PrinicpalContext(ContextType.Domain, "MyDomain"))
{
UserPrincipal user = new UserPrinicpal(pc);
User.DisplayName = "Holonka";
PrinicpalSearcher scrh = new PrinicpalSearcher(user);
Prinicpal found = scrh.FindOne();
}

}

现在它没有找到任何东西,因为没有用户它的显示名称只是“Holonka”,但我希望它找到我之前提到过的用户

非常感谢你!

c# active-directory
2个回答
0
投票

您可以在PrinicpalSearcher中使用查询字符串:

UserPrincipal user = new UserPrinicpal(pc);
User.DisplayName = "*Holonka*";
PrinicpalSearcher searcher = new PrinicpalSearcher(user);
var results = searcher.FindAll();

您还可以使用PrincipalSearcher查找具有“或”参数的用户,如下例所示:

List<UserPrincipal> searchPrinciples = new List<UserPrincipal>();
searchPrinciples.Add(new UserPrincipal(context) { DisplayName="*Holonka*"});
searchPrinciples.Add(new UserPrincipal(context) { SamAccountName = "*Holonka*" });
searchPrinciples.Add(new UserPrincipal(context) { MiddleName = "*Holonka*" });
searchPrinciples.Add(new UserPrincipal(context) { GivenName = "*Holonka*" });
List<Principal> results = new List<Principal>();
foreach (var item in searchPrinciples)
{
    var searcher = new PrincipalSearcher(item);
    // Results may contains duplicate values because of separate searchers can handle the same user
    results.AddRange(searcher.FindAll());
}

0
投票

您还可以尝试使用Ambiguous Name Resolution,这是一个特殊的AD查询,它在几个属性中查找部分匹配(这些属性的列表在该文章中)。

你不能使用qazxsw poi来使用AND。你必须使用qazxsw poi(这是PrincipalSearcher在背景中使用的)。

这是一个例子:

DirectorySearcher

使用PrincipalSearcher时,使用var searchRoot = new DirectoryEntry("LDAP://domain.com"); var searcher = new DirectorySearcher(searchRoot) { Filter = "(anr=Holonka)" }; searcher.PropertiesToLoad.Add("displayName"); using (var results in = searcher.FindAll()) { foreach (SearchResult result in results) { if (result.Properties.Contains("displayName")) { var displayName = (string) result.Properties["displayName"][0]; //do something else } } } 是明智的。如果不这样做,它将返回具有值的每个属性,这可能比您需要的数据更多。这是浪费网络流量和时间。

DirectorySearcher声明也是明智的,因为PropertiesToLoad不能被垃圾收集器彻底清理。

我在一篇文章中写了更多关于它的文章:using

© www.soinside.com 2019 - 2024. All rights reserved.