Retrieving Current Users E-mail Address from Active Directory
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://<SID={0}>", 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;
}
}









Leave a Reply