使用电子邮件ID从Active Directory查找用户名 [英] Find username from Active Directory using email id
问题描述
我正在通过传递电子邮件ID从Active Directory中找到用户名。一切正常。但是获取用户名需要30-40秒。还有其他更好的方法通过电子邮件地址从Active Directory中找到用户名吗?
I am finding user name from Active Directory by passing email id. It is working fine. But it takes 30-40 seconds to get the username. Is there any other better way to find the username from Active Directory by email address?
请参考我的代码:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
UserPrincipal userPrincipal = new UserPrincipal(context);
PrincipalSearcher principalSearch = new PrincipalSearcher(userPrincipal);
foreach (UserPrincipal result in principalSearch.FindAll())
{
if (result != null && result.EmailAddress != null && result.EmailAddress.Equals(user.Email, StringComparison.OrdinalIgnoreCase))
{
user.FirstName = result.GivenName;
user.LastName = result.Surname;
}
}
}
推荐答案
您无需枚举所有用户即可找到其中的一个!尝试以下代码:
You don't need to enumerate all users to to find one of them! Try this code:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, EmailAddress);
if (yourUser != null)
{
user.FirstName = result.GivenName;
user.LastName = result.Surname;
}
}
如果这不起作用,或者您需要要一次搜索多个条件,请使用 PrincipalSearcher
和QBE(按示例查询)方法-搜索您需要的一个用户-不要循环遍历所有用户!
If that shouldn't work, or if you need to search for several criteria at once, used the PrincipalSearcher
with the QBE (query-by-example) approach - search the one user you need - don't cycle through all users!
// create your domain context
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
// define a "query-by-example" principal -
UserPrincipal qbeUser = new UserPrincipal(ctx);
qbeUser.EmailAddress = yourEmailAddress;
// 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.....
}
}
这篇关于使用电子邮件ID从Active Directory查找用户名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!