I’ve seen several examples online of how to retrieve the logged in users e-mail address from Active Directory. Every example I see involves taking the username (via System.Enviornment.UserName) and then doing an LDAP search for that user.
A faster and more effecient way is to take the current users Sid and do Sid Binding against Active Directory. This allows you to skip the step of searching LDAP. It also keeps you from having to do the work of making sure you’re getting the right user from the right domain.
public string GetEmail()
{
//add using statement for System.Security.Principal
//Retrieve Sid of currently logged in user
WindowsIdentity user = WindowsIdentity.GetCurrent();
SecurityIdentifier userSid = user.User;
//Create LDAP path to user with Sid
string adPath = String.Format(
"LDAP://" , userSid);
//Create DE object
DirectoryEntry sidBind = new DirectoryEntry(
adPath,
null,
null,
AuthenticationTypes.Secure);
//retrieve e-mail address property
if (sidBind.Properties.Contains("mail"))
{
return sidBind.Properties["mail"].Value.ToString();
}
else
{
return String.Empty;
}
}
Related posts
Setting Up EC2 Command Line Tools on Windows
Setting Up EC2 Command Line Tools on Windows May 19th, 2009 There are some great GUI tools for working...
System.DirectoryServices Search Performance – Part 3
System.DirectoryServices Search Performance – Part 3 December 2nd, 2008 NOTE: This post is part of a series. Advanced Binding...
Speaking @ Central California .Net Users Group
7/9/09: Speaking @ Central California .Net Users Group May 6th, 2009 Presentation: Can Cloud Computing Save the World? Date:...