Find username from Active Directory using email id

前端 未结 2 856
孤街浪徒
孤街浪徒 2021-01-13 03:34

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 t

相关标签:
2条回答
  • 2021-01-13 03:50

    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!

    // 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.....          
       }
    }
    
    0 讨论(0)
  • 2021-01-13 03:53
    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();
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题