简体   繁体   English

使用电子邮件 ID 从 Active Directory 中查找用户名

[英]Find username from Active Directory using email id

I am finding user name from Active Directory by passing email id.我通过传递电子邮件 ID 从 Active Directory 中查找用户名。 It is working fine.它工作正常。 But it takes 30-40 seconds to get the username.但是获取用户名需要 30-40 秒。 Is there any other better way to find the username from Active Directory by email address?还有其他更好的方法可以通过电子邮件地址从 Active Directory 中查找用户名吗?

Please refer to my code:请参考我的代码:

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 = yourUser.GivenName;
        user.LastName = yourUser.Surname;
    }
}

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!如果这不起作用,或者如果您需要一次搜索多个条件,请将PrincipalSearcher与 QBE(按示例查询)方法一起使用 -搜索您需要的一个用户 - 不要在所有用户之间循环!

// 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.....          
   }
}
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();
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM