如何检查LDAP上是否存在用户

时间:2010-11-29 14:14:56

标签: c# .net-4.0 active-directory ldap

我需要仅使用用户名验证公司用户 - 而不是密码。

所以我需要一个像这样的方法

public bool UserExists(string username)
{ ... }

我知道System.DirectoryServices命名空间,但不知道从哪里开始。

有什么想法吗?

有80,000多条记录,所以请记住这一点。

谢谢。

修改:

我已经完成了 - 我的代码是:

private bool UserExists(string userName, string domain)
{
    try
    {
        DirectoryEntry.Exists("WinNT://" + domain + ".[hidden].com/" + userName);
        return true;
    }
    catch (COMException)
    {
        return false;
    }
}

我不知道它是否正确,但到目前为止似乎有效。

迈克尔的答案有两个相关部分:

更新#2:

我实际上用过这个:

public static bool LoggedOnUserExists()
{
    var domain = new PrincipalContext(ContextType.Domain);

    UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName);

    return foundUser != null;
}

2 个答案:

答案 0 :(得分:6)

在.NET 3.5及更高版本中,您可以使用System.DirectoryServices.AccountManagement命名空间来完成此操作:

public bool UserExists(string username)
{
   // create your domain context
   using (PrincipalContext domain = new PrincipalContext(ContextType.Domain))
   {
       // find the user
       UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.Name, username);

       return foundUser != null;
    }
}

这将使用常规用户名John Doe,或者您可以使用用户的电子邮件地址(john.doe@company.com)或其专有名称(CN=John Doe) - 请参阅IdentityType枚举必须提供: - )

答案 1 :(得分:5)

相关问题