Friday, May 11, 2012

Retrieve user’s photo from Active directory in ASP.NET

This article describes how to get the user’s photo from Active directory and display in to an aspx page. I’m creating a new ASP web application and the users photo will be displayed in Default.aspx page.  To do this you need to include 
System.DirectoryServices,  
System.DirectoryServices.AccountManagement           

assemblies to the project references.


Include following using statements in Default.aspx.cs page:


using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
 
The following method gets the users photo from the AD and return as a Bitmap.

public static Bitmap GetThumbnailPhoto(string userName)
        {
            using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain))
            {
                using (UserPrincipal userPrincipal = new UserPrincipal(principalContext))
                {
                    userPrincipal.SamAccountName = userName;
                    using (PrincipalSearcher principalSearcher = new PrincipalSearcher())
                    {
                        principalSearcher.QueryFilter = userPrincipal;
                        Principal principal = principalSearcher.FindOne();
                        if (principal!=null)
                        {
                            DirectoryEntry directoryEntry = (DirectoryEntry)principal.GetUnderlyingObject();
                            PropertyValueCollection collection = directoryEntry.Properties["thumbnailPhoto"];

                            if (collection.Value!=null && collection.Value is byte[])
                            {
                                byte[] thumbnailInBytes = (byte[])collection.Value;
                                return new Bitmap(new MemoryStream(thumbnailInBytes));
                            }                           
                        }
                        return null;
                    }
                }
            }
        }

thumbnailPhoto is the property returns the user’s thumbnail photo from the AD.


The above method gives the user's photo as bitmap. Next we have to display the image in the Default.aspx page. Add asp image control to the page.


<asp:Image ID="imbThumbnail" runat="server" />


At the Page_Load event add the image to the image control.


protected void Page_Load(object sender, EventArgs e)
        {
            Bitmap thumbnail = GetThumbnailPhoto("t-ictdev05");

            String saveImagePath = Server.MapPath("~/Images/image.jpg");
            thumbnail.Save(saveImagePath, ImageFormat.Jpeg);
            imbThumbnail.ImageUrl = "~/Images/image.jpg";
        }
 
To set the ImageUrl, I am saving the image to Images/image.jpg and displaying the photo.

 

1 comment: