如何从AD检索登录的用户图像?

时间:2013-11-26 13:53:33

标签: asp.net

  

我有我的代码来检索已记录的用户详细信息,但每件事情都可以   我无法检索用户图像。

DirectorySearcher searcher = new DirectorySearcher();
        searcher.SearchScope = SearchScope.Subtree;
        searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", Environment.UserName);
        //SearchResult findUser = searcher.FindOne();
        foreach (SearchResult findUser in searcher.FindAll())
        {
            if (findUser != null)
            {
                DirectoryEntry user = findUser.GetDirectoryEntry();
                string userName = user.Properties["displayName"].Value.ToString();
                string departement = user.Properties["Department"].Value.ToString();
                string title = user.Properties["title"].Value.ToString();
                string[] rt = new string[] { Login, userName, Email, Mobile };

                Lbl_User.Text = userName;
                Lbl_Administrative.Text = departement;
                Lbl_Position.Text = title;

            }
        }

2 个答案:

答案 0 :(得分:1)

我刚刚接受了你的代码并用它来制作一个方法来检索图像。你需要重构它,要么只得到byte [],要么得到整个图像。

//add this
using System.Drawing;

static Image GetPhotoFromAD(string userName)
{
    DirectorySearcher searcher = new DirectorySearcher();
    searcher.SearchScope = SearchScope.Subtree;
    searcher.Filter = string.Format(CultureInfo.InvariantCulture, "(sAMAccountName={0})", userName);
    //SearchResult findUser = searcher.FindOne();
    foreach (SearchResult findUser in searcher.FindAll())
    {
       if (findUser != null)
       {
          byte[] photodata = findUser.Properties["jpegPhoto"].Value as byte[];
          using (MemoryStream str = new MemoryStream(photodata))
          {
             return Bitmap.FromStream(str);
          }
        }
    }
}

如果您只想要原始数据,则重要位为byte[] photodata = user.Properties["jpegPhoto"].Value as byte[];

答案 1 :(得分:0)

二进制图像应存储在名为thumbnailPhoto的属性中。

      var photo = user.Properties["thumbnailPhoto"];
      if (photo != null) {
        byte[] buffer = (byte[])photo.Value;
        //var bitmap = new Bitmap(new MemoryStream(buffer, false));
        //bitmap.Save(@"c:\test.bmp");
      }

现在,鉴于您将问题标记为asp.net,您必须编写通用处理程序(.ashx)来检索图像。此处理程序应编写

的内容
      photo.Value

进入响应输出流并将内容类型设置为image / bmp

在你的控件/页面中,只需引用像

这样的处理程序
<img src="/GenericHandler.ashx" alt="My image" />