.NET offers a rich API for both Windows and Web development.  In a recent side project, I needed to develop a way to query Active Directory (AD) to retrieve user information; particurlaly the emails of the user.  Fortunetely, .NET has the System.DirectoryServices.dll assembly to make this task easy!

The System.DirectoryServices namespace is the home for two very useful component classes, the DirectoryEntry and DirectorySearcher classes.  These classes use the Active Directory Services Interfaces (ADSI) to provide a easy, managed-code method for interacting with a variety of network providers.  For this quick article, I will use ADSI to programatically interact with Active Directory.

First, I need to create a DirectoryEntry object to point at the root of my Active Directory domain.  Here's a quick example:

//Get the username and domain information
string userName = Environment.UserName;
string domainName = Environment.UserDomainName;

//Set the correct format for the AD query and filter
string ldapQueryFormat = @"LDAP://{0}.com/DC={0},DC=com";
string queryFilterFormat = @"(&(samAccountName={0})(objectCategory=person)(objectClass=user))";

SearchResult result = null;
using(DirectoryEntry root = newDirectoryEntry(rootQuery))
{
    using(DirectorySearcher searcher = new DirectorySearcher(root))
    {
        searcher.Filter = searchFilter;
        SearchResultCollection results = searcher.FindAll();

        result = (results.Count != 0) ? results[0] : null;

    }
}

To get the value of the primary email, you need to access the Properties collection using the mail dictionary index.  Doing so, the object returned from this indexer is a PropertyValueCollection object.  An object used to hold the values of a DirectoryEntry property.  Here's the full example:

//Get the email property from AD
string primaryEmail = result.Properties["mail"][0] as string;

Here comes the fun part; getting the rest of the emails for this user!  Fortunately, the proxyaddresses property holds all the emails for the user (To put it into perspective, this is the Email Addresses tab for a user's properties under Active Directory Users and Computers in your Win2x domain controller).  However, this property lists all email address types, such as SMTP, x.400, etc.  So we will need to modify our code to check for the SMTP type.  Since all the values for this property are strings, we can use a simple foreach loop to cast the objects up to a string and store them in a StringCollection object.

StringCollection emails = new StringCollection();
try

{
    foreach(string proxyAddr in dirResult.Properties["proxyaddresses"])
    {
        //Make it 'case-insensative'
        if(proxyAddr.ToLower().StartsWith("smtp:"))

        //Get the email string from AD
        email.Add(proxyAddr.Substring(5));
    }
}
//Do nothing for any errors, make the collection null
catch
{
    emails = null;
}


After this code snippet, the emails  object contains all the SMTP emails for the user or it's set to null.  You can now iterate through this collection and output all the email addresses for this user.