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

标签 c# c#-4.0 active-directory

我通过传递电子邮件 ID 从 Active Directory 中查找用户名。它工作正常。但是获取用户名需要 30-40 秒。还有其他更好的方法可以通过电子邮件地址从 Active Directory 中查找用户名吗?

请引用我的代码:

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

最佳答案

您无需枚举所有 用户即可找到其中一个!试试这个代码:

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(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.....          
   }
}

关于c# - 使用电子邮件 ID 从 Active Directory 中查找用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38801217/

相关文章:

c# - 内部类成员/属性可见性 (C#)

c# - 是否有必要为 n 层架构上的每一层编写单元测试代码?

使用 HTMLHelper 和 "All"选择下拉列表值的 JavaScript 在 ASP .NET MVC4 中不起作用

azure - 使用客户的 Active Directory(Azure 或 ADFS)对 UWP 客户端和 .Net Core Web 应用程序进行身份验证

powershell - 如何使用 powershell 对 Active Directory 中的用户进行身份验证

c# - `AsyncLocal` 是否也做 `ThreadLocal` 做的事情?

c# - 更新数据库中的第一行 C# mysql

windows - 如何检查 Windows 计算机加入的 Azure AD 域的名称?

.net - 如何使用 Socket 和 Reactive 扩展(Rx)从连接的客户端套接字获取接收到的消息缓冲区

.net - C#在依赖于继承类初始化的基类上执行代码