Retrieving the Logged-in User’s Email via AD
by Warlock on Apr.02, 2009, under .NET
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:
- Use the AD administrative classes to determine the active domain
- Convert the domain into a valid LDAP path to act as the root of the query
- Create a filter for the LDAP query using the login name of the user
- 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.
April 7th, 2009 on 12:04 pm
Check out http://serktools.com/2009/04/07/retrieving-current-users-e-mail-address-from-active-directory/ for an alternative that is a little more efficient if you have the users SID.