Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/339.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何检查LDAP上是否存在用户_C#_.net 4.0_Active Directory_Ldap - Fatal编程技术网

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

C# 如何检查LDAP上是否存在用户,c#,.net-4.0,active-directory,ldap,C#,.net 4.0,Active Directory,Ldap,我需要只使用用户名而不是密码来验证公司中的用户 所以我需要一个这样的方法 public bool UserExists(string username) { ... } 我知道System.DirectoryServices名称空间,但不知道从哪里开始 有什么想法吗 有80000多条记录,所以请记住这一点 多谢各位 编辑: 我已经做到了-我的代码是: private bool UserExists(string userName, string domain) { try {

我需要只使用用户名而不是密码来验证公司中的用户

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

public bool UserExists(string username)
{ ... }
我知道
System.DirectoryServices
名称空间,但不知道从哪里开始

有什么想法吗

有80000多条记录,所以请记住这一点

多谢各位

编辑:

我已经做到了-我的代码是:

private bool UserExists(string userName, string domain)
{
    try
    {
        DirectoryEntry.Exists("WinNT://" + domain + ".[hidden].com/" + userName);
        return true;
    }
    catch (COMException)
    {
        return false;
    }
}
我不知道它是否正确,但到目前为止似乎有效

Michael的回答有两个相关部分:

更新#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=johndoe
)-查看
IdentityType
枚举必须提供的功能:-)

您不应该再使用WinNT提供程序-这严格是为了向后兼容,但它通常在广告网络中无法正常工作我假设在当前域上搜索?是否仍要使用此方法并指定域?@Eddie:sure-the,它允许您指定域和/或该域中用于搜索的容器