Pages

Friday, May 17, 2013

Get Active Driectory Information using ASP.Net Code


You can get the below details from AD:

Get the AD First Name
Get the AD Last Name
Get the AD Email
Get the AD Designation
Get the AD Department

Use in the following Namespace :

using System.DirectoryServices;

protected string GetADUserInfo(string AccountName)
        {
            //try
            //{

            // pass the account name as "jtan" remove the Domain name and "\\".
            //production
            string ldapQueryFormat = @"LDAP://DC=APACS,DC=STARS";
            //VPC
            //string ldapQueryFormat = @"LDAP://DC=APACS,DC=local";

            string queryFilterFormat = @"(&(samAccountName=" + AccountName + ")
(objectCategory=person)(objectClass=user))";
            string email = "";
            //production
            using (DirectoryEntry root = new DirectoryEntry(ldapQueryFormat, "APAC\
\Adminshrp", "Newuser1"))
            //VPC
            //using (DirectoryEntry root = new DirectoryEntry(ldapQueryFormat, "APAC\
\Administrator", "p@ssw0rd"))
            {
                using (DirectorySearcher searcher = new DirectorySearcher(root))
                {
                    searcher.Filter = queryFilterFormat;
                    SearchResult result = searcher.FindOne();
                    DirectoryEntry dr = result.GetDirectoryEntry();
                    if (dr.Properties.Count > 0)
                    {
                        email = dr.Properties["mail"][0].ToString();
                    }
                }
            }
            return email;
            //}
            //catch (Exception ex)
            //{
            //    lblError.Text = ex.Message + "--" + ex.StackTrace;
            //}
        }

No comments:

Post a Comment