Like, uh, whatever, I guess


  Friday, May 21, 2004
    [4:16:15 PM]

Lookup a users 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("SAM Account Name");

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</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;

Original article: http://www.123aspx.com/redir.aspx?res=30841

Comments: Post a Comment

November 2003
January 2004
February 2004
March 2004
April 2004
May 2004
June 2004

This page is powered by Blogger. Isn't yours?  Weblog Commenting and Trackback by HaloScan.com