Tag Archives: Active Directory

Retrieving the Logged-in User’s Email via AD

I was writing a test utility yesterday and I wanted to get the email address for the user who is currently logged into the computer. The only way I could think of was to query Active Directory for it, so I ended up with the following code:

using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;

private string GetCurrentUserEmailAddress()
    string ldapPath = "";
    string filter = "";

       Domain d = Domain.GetCurrentDomain();
       foreach (string e in d.Name.Split('.'))
           if (ldapPath.Length > 0)
               ldapPath += ",";

           ldapPath += "DC=" + e;

       ldapPath = "LDAP://" + ldapPath;
       filter = "(&(objectClass=user)(SAMAccountName=" 
                     + System.Environment.UserName + "))";

       DirectoryEntry de = new DirectoryEntry(ldapPath);
       DirectorySearcher ds = new DirectorySearcher();
       ds.Filter = filter;

       SearchResult sr = ds.FindOne();

       if (null == sr)
           throw new Exception("Failed to get user for path '" 
                    + ldapPath + "' and filter '" + filter + "'.");

       return sr.Properties["mail"][0].ToString();

The basic gist of it is as follows:

  1. Use the AD administrative classes to determine the active domain
  2. Convert the domain into a valid LDAP path to act as the root of the query
  3. Create a filter for the LDAP query using the login name of the user
  4. Run the query against AD and pull down the user’s email address

I’ve only tested the above code on a few computers but it seems to work.