0

Check for User existence in Active Directory (Domain) using C# and AccountManagement API

by Syed Aziz ur Rahman 10. December 2013 08:02

 

System.DirectoryServices.AccountManagement API has been added to .net in version 3.5. The API makes it very easy to manage Active Directory (Domain) using code (e.g. C# ). The API lets you perform different operations like add user, delete user, check for user existence in very Object Oriented way as compare to the old API i.e. (DirectoryEntry)

To use the API, you have to add reference to "System.DirectoryServices.AccountManagement.dll" in your project.

Here is some basic code to check if the user exist in Active Directory

 

private string OU = "CN=Users,DC=test,DC=domainName,DC=com";
private string adminUserName = "testAdmin";
private string adminPassword = "T3st123";
string domainName = "Test.DomainName.com";

private void Form1_Load(object sender, EventArgs e)
{
    try
    {        
        if (CheckUserExist("testUser"))
        {
            MessageBox.Show("User found");
        }
    }
    catch (AuthenticationException secEx)
    {
        MessageBox.Show(secEx.ToString());
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    this.Close();
}

private bool CheckUserExist(string samAccountName)
{
    //Use admin account if current user does not have Active Directory rights.
    using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domainName, OU, ContextOptions.SimpleBind, adminUserName, adminPassword))
    {
        //validate the credentials of admin user.
        if (context.ValidateCredentials(adminUserName, adminPassword))
        {
            UserPrincipal existedUserPrincipal = new UserPrincipal(context);
            existedUserPrincipal.SamAccountName = samAccountName;
            PrincipalSearcher searcher = new PrincipalSearcher(existedUserPrincipal);
            if (searcher.FindOne() != null)
            {
                return true;
            }
        }
    }
    return false;
}

Tags:

DotNet

Powered by BlogEngine.NET 2.5.0.6
Original Design by Laptop Geek, Adapted by onesoft