Mar 8, 2016

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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;
}

0 comments:

Post a Comment

Nam Le © 2014 - Designed by Templateism.com, Distributed By Templatelib