C# - SPLessons

Check UserID exists in Active Directory

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Check UserID exists in Active Directory

Check UserID exists in Active Directory

Hi every one today we are going to see whether a user exist in the active directory or not using C#.

 

 

  1.  Please add the System.DirectoryServices.AccountManagement namespace and assembly to your code.

public string DoesUserExist(string userName)
        {

            using (var domainContext = new PrincipalContext(ContextType.Domain, "spl"))
            {
                using (var foundUser = UserPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, userName))
                {
                    if (foundUser != null)
                        return foundUser.Name;
                    else
                        return "User Does not exist ";
                }
            }

        }