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 userWindowsIdentity 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 propertyif (sidBind.Properties.Contains("mail"))
{return sidBind.Properties["mail"].Value.ToString();
}
else { return String.Empty;}
}
Steve Evans has worked in the IT field for over 12 years, specializing in Microsoft technologies. He has consulted for small businesses on their IT infrastructure needs as well as worked for larger companies as a Systems Engineer. Steve has been a recipient of the Microsoft Most Valuable Professional (MVP) award for the past 3 years, and is a Technical Speaker at various industry events.







Leave a Reply