Monday, March 18, 2013

Easy way to validate User againsts Active Directory in C#.

If you want to validate a user against an active directory. This is the easiest way provided by .Net framework. By using this we do not need to explicitly create a LDAP web service reference. For validating user we need to include this System.DirectoryServices.AccountManagement.dlll reference in our solution. After adding this dll our code will be very simple,  here it is :

Include this two Namespace (You can resolve it as well) :

using System.DirectoryServices;
using System.DirectoryServices.AccountManagement; 




Here I am taking value to validate a from a text box.

string Domain = string.Empty;
string UserName = string.Empty;
string strUserName = txtAdminName.Text;
 

if (!string.IsNullOrEmpty(strUserName))
 {
 string[] DomainAndUserName = strUserName.Split('\\');

                 if (DomainAndUserName != null && DomainAndUserName.Length > 0)
                       {
                            Domain = DomainAndUserName[0];
                            UserName = DomainAndUserName[1];
                        }
                    }
                    using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
                    {
                        UserPrincipal up = UserPrincipal.FindByIdentity(pc, strUserName);
                        bool UserExists = (up != null);
                        if (UserExists)

                        {
                        // Do whatever action you want to perform, when user exists.
                        }
                        else
                       {
                        // Do whatever action you want to perform, when user does not exist.              
                        }
                     }
   }

You can place this code in a  function and then use. Hope it helps...!!