Check UserID exists in Active Directory using C#

后端 未结 2 1084
长发绾君心
长发绾君心 2020-12-13 09:45

How can we check whether the USERID exists in Active Directory or not.

I have LDAP String and UserID, can I find whether that UserID exists in Active Directory or no

相关标签:
2条回答
  • 2020-12-13 10:19

    You can do something along the lines of (replacing domain with the domain you're authenticating against or removing the parameter altogether):

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

    To achieve checking for if a user exists. This comes from the System.DirectoryServices.AccountManagement namespace and assembly.

    You can find more information at http://msdn.microsoft.com/en-us/library/system.directoryservices.accountmanagement.aspx

    You may want to check more into PrincipalContext as it has interesting methods for authenticating user credentials and such.

    0 讨论(0)
  • 2020-12-13 10:29

    I would use the System.DirectoryServices.AccountManagement namespace.

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

    See http://msdn.microsoft.com/en-us/library/bb344891.aspx for more info

    0 讨论(0)
提交回复
热议问题