使用电子邮件id从活动目录查找用户名

本文关键字:查找 用户 活动 电子邮件 id | 更新日期: 2023-09-27 18:01:15

我通过传递电子邮件id从Active Directory查找用户名。它工作得很好。但是获取用户名需要30-40秒。有没有其他更好的方法从活动目录中通过电子邮件地址查找用户名?

请参考我的代码:

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;
        }
    }
}

使用电子邮件id从活动目录查找用户名

您不需要枚举所有用户来查找一个 !试试下面的代码:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{
    UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, EmailAddress);
    if (yourUser != null)
    {
        user.FirstName = yourUser.GivenName;
        user.LastName = yourUser.Surname;
    }
}

如果那不应该工作,或者如果您需要一次搜索多个条件,使用PrincipalSearcher与QBE(按例查询)方法- 搜索您需要的一个用户-不要循环遍历所有用户!

// create your domain context
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "domainname"))
{    
   // define a "query-by-example" principal - 
   UserPrincipal qbeUser = new UserPrincipal(context);
   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.....          
   }
}
using System.DirectoryServices.AccountManagement;
// Lock user
using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    UserPrincipal yourUser = UserPrincipal.FindByIdentity(context, logonName);
    if (yourUser != null)
    {
        if(!yourUser.IsAccountLockedOut())
        {
            yourUser.Enabled = False;
            yourUser.Save();
        }
    }
}