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.
cool, thanks.
ReplyDeleteis it good also on dot.net maybe?
active directory photo