Skip to content

Instantly share code, notes, and snippets.

Created January 15, 2014 19:30
Show Gist options
  • Save anonymous/8442783 to your computer and use it in GitHub Desktop.
Save anonymous/8442783 to your computer and use it in GitHub Desktop.
In C#, fetch an Active Directory user's full name and email address given only their username. Pretty much just implemented this: http://stackoverflow.com/questions/785527/get-mail-address-from-activedirectory
using System;
using System.DirectoryServices;
namespace EmailAddressTest
{
class Program
{
static void Main(string[] args)
{
do
{
Console.WriteLine();
Console.WriteLine("------------------");
String username = Environment.UserName;
Console.WriteLine("Enter the username in question [leave blank for {0}]:", username);
String newUsername = Console.ReadLine();
if (!string.IsNullOrWhiteSpace(newUsername)) username = newUsername;
// get a DirectorySearcher object
var entry = new DirectoryEntry();
var search = new DirectorySearcher(entry);
// specify the search filter
search.Filter = "(&(objectClass=user)(anr=" + username + "))";
// specify which property values to return in the search
search.PropertiesToLoad.Add("givenName"); // first name
search.PropertiesToLoad.Add("sn"); // last name
search.PropertiesToLoad.Add("mail"); // smtp mail address
// perform the search
SearchResult result = search.FindOne();
if (result == null)
{
Console.WriteLine("*** user {0} not found", username);
}
else
{
Console.WriteLine("Name = {0} {1}", result.Properties["givenName"][0], result.Properties["sn"][0]);
Console.WriteLine("Email = {0}", result.Properties["mail"][0]);
}
Console.WriteLine("press 'y' to try again, any other key to exit.");
} while (Console.ReadKey().KeyChar.ToString().ToLower() == "y");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment