How to get Active Directory (LDAP) User Details with C #

To get Active Directory user details form ASP.Net

Add DLL Reference  :  System.DirectoryServices;

C#  Code :

////Domain Name or DomainPath
string path = “LDAP://Domain.local”;

string username = String.Format(“{0}”, Request.Form[“username”]);
string password =String.Format(“{0}”, Request.Form[“password”]);

DirectoryEntry de = new DirectoryEntry(path, username, password, AuthenticationTypes.Secure);

DirectorySearcher ds = new DirectorySearcher(de);

ds.Filter = “(&(objectCategory=person)(samAccountName=”+ username +”))”;

SearchResult result = ds.FindOne();

if (result != null)
{
string firstName = string.Empty;
string lastname = string.Empty;

if (result.Properties[“givenName”].Count > 0)
{
firstName = result.Properties[“givenName”][0].ToString();
}

if (result.Properties[“sn”].Count > 0)
{
lastname = result.Properties[“sn”][0].ToString();
}

Session[“Username”] = firstName + ” ” + lastname;

return true;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s