Friday, January 9, 2009

C# How to: Retreive the logged on users email from Active Directory

Below is a quick example on how to display information from a user's Active Directory profile into a web page. This example displays the AD users email address.

1. If you're using asp.net create a class file ADInfo.cs in your App_Code folder and insert the below code.

//---------ADInfo.cs--------------------------------
using System.DirectoryServices;

public class ADInfo
{

private DirectoryEntry GetDirectoryObject()
{
DirectoryEntry oDE;
oDE = new DirectoryEntry("LDAP://server/dc=w3portals,dc=com", @"W3\" + "adminuser", "password", AuthenticationTypes.Secure);
return oDE;
}

public DirectoryEntry GetUser(string UserName)
{
DirectoryEntry de = GetDirectoryObject();
DirectorySearcher deSearch = new DirectorySearcher();
deSearch.SearchRoot = de;

deSearch.Filter = "(&(objectClass=user)(SAMAccountName=" + UserName + "))";
deSearch.SearchScope = SearchScope.Subtree;
SearchResult results = deSearch.FindOne();

if (!(results == null))
{
de = new DirectoryEntry(results.Path, "adminuser", "password", AuthenticationTypes.Secure);
return de;
}
else
{
return null;
}
}
//-----------------------------------------

2. Create a label on your aspx page called 'lblEmail'
3. In the codefile of your aspx page copy this code.


//------Default.aspx.cs---------

protected void Page_Load(object sender, EventArgs e)
{
string[] FullUserName = User.Identity.Name.ToString().Split('\\');
ADInfo adi = new ADInfo();
DirectoryEntry dirEntry = adi.GetUser(FullUserName[1].ToString());
lblEmail.Text = dirEntry.Properties["mail"].Value.ToString();
}

//----------------------------

Also, I plan to list other useful Active Directory user properties in my next post. Hope this is useful.

1 comment:

Sabry said...

Thank you for the good code example, most of the other tutorials had too much of detail and the code was not this clear.