c# Get Email Address from Active Directory (using Username) in Asp.net

dirSometimes it’s handy to grab either a username or email address (why not both?) from active directory. Below are the steps I believe you’ll need to get going quickly. In my example, I’m using VS2012 and .net 4.5.

1. Set your app to use windows authentication, you’ll need to set these to debug in VS:

Your web.config:

    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <authentication mode="Windows" />
    <identity impersonate="true" />

      <allow users="*" />

    <validation validateIntegratedModeConfiguration="false" />

Your project settings:


2. Now in your application, add a reference to System.DirectoryServices:


3. And in your code file:

using System.DirectoryServices;

4. A little function to search through active directory:

 private string uEmail(string uid)
            DirectorySearcher dirSearcher = new DirectorySearcher();
            DirectoryEntry entry = new DirectoryEntry(dirSearcher.SearchRoot.Path);
            dirSearcher.Filter = "(&(objectClass=user)(objectcategory=person)(mail=" + uid + "*))";

            SearchResult srEmail = dirSearcher.FindOne();

            string propName = "mail";
            ResultPropertyValueCollection valColl = srEmail.Properties[propName];
                return valColl[0].ToString();
                return "";


5. And finally, how you can use:

string uName = "";
uName = uEmail(HttpContext.Current.User.Identity.Name.Replace(@"yourdomain\", ""));

Hope you enjoy! You can also use this method to retrieve other AD details (groups, full name, etc.).

c# Get Email Address from Active Directory (using Username) in Asp.net

One thought on “c# Get Email Address from Active Directory (using Username) in Asp.net

  1. mohy says:

    thank for your article it is useful.
    but I want register an online user by a web form and add them to active directory(i read very page about it and this is simple by using account management class) and then enable mail box for that user in exchange 2013 and ldap Schema and finally add Scheduler meeting time for them.
    can help me?
    I am new in c# and asp.net


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s