Lookup an email address using Active Directory
Based on some VB.net code I found on 123aspx.com, I knocked up a little class in C# that given a SAM account name, returns the first email address it encounters in active directory.
The class is called ActiveDirectoryHelper.
To use the class, do something like this:
string emailAddress = ActiveDirectoryHelper.GetEmailAddress("Luke.Latimer");
Here's the code verbatim:
using System;
using System.DirectoryServices;
namespace Numerica.Core.Util
{
/// <summary>
/// <c>ActiveDirectoryHelper</c> contains a number of static methods
/// to assist with using Active Directory
/// </summary>
public class ActiveDirectoryHelper
{
private static string _path = "LDAP://DOMAINNAME.TLD/DC=DOMAINNAME,DC=TLD";
/// <summary>
/// Private constructor as methods are all static
/// </summary>
private ActiveDirectoryHelper()
{
}
/// <summary>
/// Queries Active Directory for Numerica.ads for a users email address.
/// </summary>
/// <param name="samAccountName">The users SAM account name, i.e. Luke.Latimer, or RPM</param>
/// <returns>The first email address that is returned by AD, null if no results are found</returns>
public static string GetEmailAddress(string samAccountName)
{
string rtn = null;
DirectoryEntry directory = new DirectoryEntry(_path);
DirectorySearcher searcher = new DirectorySearcher(directory);
// Build LDAP searcher
searcher.Filter = "(&(objectClass=user)(samaccountname=" + samAccountName + "))";
SearchResultCollection resultCollection = searcher.FindAll();
// No need to proceed if there aren't any results
if ( resultCollection.Count > 0 )
{
SearchResult result = resultCollection[0]; // Just use the first result
ResultPropertyCollection resultProperties = result.Properties;
rtn = resultProperties["mail"][0].ToString(); // Just get the first email address
}
return rtn;
}
}
}