[英]Get multiple user with similar names from Active Directory using C#
I need to display a list of users (in autocomplete) with similar names from the AD. 我需要显示广告中具有相似名称的用户列表(自动填充)。 For example, if I search Arthur and there are 2 people with same name (first name or last name), I should display both the names in the autocomplete.
例如,如果我搜索亚瑟,并且有两个人具有相同的名字(名字或姓氏),则我应该在自动填充中同时显示两个名字。 I tried to get the names but it is taking around 2-4 minutes to get the names.
我尝试获取名称,但是获取名称大约需要2-4分钟。 I am using the following code:
我正在使用以下代码:
string[] domainNames = new string[] { "domain1", "domain2" };
List<string> userNames = new List<string>();
string user = string.Empty;
foreach (string domain in domainNames)
{
using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, domain))
{
GroupPrincipal group = GroupPrincipal.FindByIdentity(pc, IdentityType.SamAccountName, "Domain Users");
if (group != null)
{
foreach (Principal p in group.GetMembers(false))
{
if (p.Name.ToLower().Contains(key.ToLower()))
{
if (!userNames.Contains(p.Name))
userNames.Add(p.Name);
}
}
}
}
}
Any way I can speed up the process? 有什么办法可以加快这个过程吗? I am already using ajax call.
我已经在使用ajax了。
The cn=
filter isn't really valid - there's nothing guaranteeing that format. cn=
过滤器实际上不是有效的-不能保证该格式。 Instead, look up Ambigous Name Resolution - it's designed for this: http://social.technet.microsoft.com/wiki/contents/articles/22653.active-directory-ambiguous-name-resolution.aspx . 取而代之的是,查找Ambigous名称解析-为此而设计: http ://social.technet.microsoft.com/wiki/contents/articles/22653.active-directory-ambiguous-name-resolution.aspx。
DirectorySearcher ds = new DirectorySearcher();
ds.SearchRoot = new DirectoryEntry("LDAP://" + domain, domain + @"\" + userName, password);
ds.Filter = "(&(objectClass=user)(cn=*" + key + "*))";
ds.PropertyNamesOnly = true;
ds.PropertiesToLoad.Add("name");
ds.PropertiesToLoad.Add("cn");
foreach (SearchResult searchResults in ds.FindAll())
{
foreach (string propertyName in searchResults.Properties.PropertyNames)
{
foreach (Object retEntry in searchResults.Properties[propertyName])
{
var user = retEntry.ToString().Split('/').Where(x => x.Contains("CN")).Select(y => y).FirstOrDefault().Split(',').Where(z => z.Contains("CN")).Select(c => c).FirstOrDefault().Split(',').FirstOrDefault().Split('=')[1];
if(!string.IsNullOrWhiteSpace(user))
userNames.Add(user);
}
}
}
Reduced to 30-40 seconds. 减少到30-40秒。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.