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:

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

    <authorization>
      <allow users="*" />
    </authorization>
  </system.web>

  <system.webServer>
    <validation validateIntegratedModeConfiguration="false" />
  </system.webServer>
</configuration>

Your project settings:

vs_winauth

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

dirservices

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];
            try
            {
                return valColl[0].ToString();
            }
            catch
            {
                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