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

我需要使用他们的用户名来validation公司中的用户 – 而不是他们的密码。

所以我需要这样的方法

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

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

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

  • http://www.codeproject.com/KB/system/everythingInAD.aspx#22
  • http://www.codeproject.com/KB/system/everythingInAD.aspx#35

更新#2:

我实际上用过这个:

 public static bool LoggedOnUserExists() { var domain = new PrincipalContext(ContextType.Domain); UserPrincipal foundUser = UserPrincipal.FindByIdentity(domain, IdentityType.SamAccountName, Environment.UserName); return foundUser != null; } 

在.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枚举的含义报价:-)

好文章开始:

Howto :(几乎)通过C#在Active Directory中的一切