Retrieving Current Users E-mail Address from Active Directory

admin Last updated on: April 13, 2023

Retrieving Current Users E-mail Address from Active Directory

April 7th, 2009

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

History Speaking History Portland Code Camp, May 2009 Networking for Developers (Highest Interested Ranking) Can Cloud Computing Save the...

Cloud Computing & Virtual Servers Where Should You Deploy Your Application So many companies are looking at cloud computing...

IIS 7.5 for IT Pros IIS 7.5 for IT Pros – Slide Deck Learn how to setup, configure, and...

Setting Up EC2 Command Line Tools on Windows

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

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

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:...