使用C#检查Active Directory中是否存在UserID

msb*_*uva 26 c# active-directory userid

我们如何检查USERID中是否存在USERID.

我有LDAP String和UserID,我可以找到Active Directory中是否存在该UserID.我在ASP.NET Web应用程序(.NET 3.5)中使用它

Jos*_*ers 46

您可以执行某些操作(使用您要进行身份验证的域替换域或完全删除参数):

public bool DoesUserExist(string userName)
{
    using (var domainContext = new PrincipalContext(ContextType.Domain, "DOMAIN"))
    {
        using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
        {
            return foundUser != null;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

实现检查用户是否存在.这来自System.DirectoryServices.AccountManagement命名空间和程序集.

您可以在http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx上找到更多信息.

您可能希望更多地检查PrincipalContext,因为它有用于验证用户凭据等的有趣方法.

  • +1我会做什么,只能更好地解释.此外,您可以省略doamin名称以使用本地域 - 如果您只有一个域并且不需要知道其名称,则可以使用. (3认同)

Grh*_*rhm 8

我会使用System.DirectoryServices.AccountManagement命名空间.

string UserID = "grhm";
bool userExists = false;

using (var ctx = new PrincipalContext(ContextType.Domain))
{
    using (var user = UserPrincipal.FindByIdentity(ctx, UserID))
    {
        if (user != null)
        {
            userExists = true;
            user.Dispose();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅http://msdn.microsoft.com/en-us/library/bb344891.aspx