I am trying to read user image from Active Directory in C#. I am new to this and I have tried many online solutions.
In most cases they have used bitmap but for me somehow bitmap is not working as it fails to find reference even though I have added System.Drawing.Common
. So I have tried another way but still I couldn't get it done. I am able to get the data in byte[]
but somehow I'm unable to pass it to a memoryStream
.
Here is my code:
private User LookUpUserInActiveDirectory(string emailId)
{
User ldapUser = new User();
try
{
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, this.activeDirectoryConfiguration.PrincipalContextName, this.activeDirectoryConfiguration.PrincipalContextContainer, this.activeDirectoryConfiguration.UserName, this.activeDirectoryConfiguration.Password))
{
using (UserPrincipal userPrincipal = new UserPrincipal(ctx))
{
userPrincipal.EmailAddress = emailId;
// create your principal searcher passing in the QBE principal
using (PrincipalSearcher srch = new PrincipalSearcher(userPrincipal))
{
using (UserPrincipal results = (UserPrincipal)new PrincipalSearcher(userPrincipal).FindOne())
{
if (results != null)
{
// DirectoryEntry de = results.GetUnderlyingObject() as DirectoryEntry;
DirectoryEntry directoryEntry = (DirectoryEntry)results.GetUnderlyingObject();
// DirectoryEntry directoryEntry = (DirectoryEntry)results.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));
}
ldapUser.Name = results.DisplayName;
ldapUser.EmailId = results.EmailAddress;
using (DirectorySearcher dsSearcher = new DirectorySearcher())
{
dsSearcher.Filter = "(&(objectCategory=person)(sAMAccountName=*)(mail=" + ldapUser.EmailId + "))";
SearchResult res = dsSearcher.FindOne();
using(DirectoryEntry user=new DirectoryEntry(res.Path))
{
byte[] data = user.Properties["thumbnailPhoto"].Value as byte[];
//if (data != null)
//{
// using(MemoryStream s= new MemoryStream(data))
// {
// Bitmap.FormStream(s);
// }
//}
var fs = new MemoryStream();
var wr = new BinaryWriter(fs);
wr.Write(data);
wr.Close();
Console.WriteLine(fs);
}
}
}
}
}
catch (Exception)
{
ldapUser = null;
}
return ldapUser;
}
Can anyone help me with this ?