Retrieve Active Directory User Photos in C#

Newer versions of Office (2010+) use Active Directory to retrieve and display user photos. It’s a useful feature that also adds visual interest. I can look quickly at the thumbnails at the bottom of an email or meeting request in Outlook to see who’s invited; this is much faster than reading through the semi-colon delimited list of email addresses.

I’m working on a TFS application that has some custom views. I thought it would be cool to display the user as a thumbnail instead of simply using their name. Doing this will add some pizzazz and, ultimately, result in a cleaner UI since vertical space is more abundant in my layout–it is less costly for me to show a 50×50 thumbnail than to display a 20×100 textbox.

So how do we do it? Like many tasks, the .NET Framework makes it relatively easy for us once we know what we’re doing. Here are the steps:

  1. Bind to a node in Active Directory Domain Services with the DirectoryEntry class
  2. Use the DirectorySearcher class to specify a search filter and find the desired user
  3. Extract the image bytes from the user properties
  4. Convert the bytes to a usable format

The method below accepts a username parameter, looks it up in AD, and binds the thumbnail to an Image. (Note that this is a WPF application, which is why I convert to the BitmapImage class. You may want to convert to a different type, like System.Drawing.Bitmap.)

private void GetUserPicture(string userName)
{
    var directoryEntry = new DirectoryEntry("LDAP://YourDomain");
    var directorySearcher = new DirectorySearcher(directoryEntry);
    directorySearcher.Filter = string.Format("(&(SAMAccountName={0}))", userName);
    var user = directorySearcher.FindOne();

    var bytes = user.Properties["thumbnailPhoto"][0] as byte[];

    using (var ms = new MemoryStream(bytes))
    {
        var imageSource = new BitmapImage();
        imageSource.BeginInit();
        imageSource.StreamSource = ms;
        imageSource.EndInit();

        uxPhoto.Source = imageSource;
    }
}