You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# 从Active Directory读取用户图片失败,Bitmap引用与字节流处理问题求助

问题排查与解决方案

1 Bitmap引用缺失问题

.NET Core 3.0及以上版本中,System.Drawing.Common包默认仅支持Windows平台:

  • 若你的项目仅运行在Windows环境,可在项目文件(.csproj)的PropertyGroup节点中添加配置<EnableWindowsTargeting>true</EnableWindowsTargeting>,同时将目标框架调整为带Windows后缀的版本(如net6.0-windows)即可正常引用Bitmap类。
  • 若项目需要跨平台运行,可替换使用跨平台图像处理库如SixLabors.ImageSharp,无需依赖System.Drawing。
  • 若你的需求只是存储、返回图片,不需要裁剪、修改等操作,完全可以直接使用读取到的byte[],不需要转Bitmap对象。

2 字节数组处理的现有代码问题

你当前的代码存在3处明显问题:

  • 冗余查询:已经通过UserPrincipal获取到了DirectoryEntry对象,不需要再初始化DirectorySearcher重复查询AD,既浪费性能也容易出错。
  • 流处理逻辑错误:不需要用BinaryWriter往MemoryStream写数据,直接用读取到的byte[]初始化MemoryStream即可,你当前关闭BinaryWriter的同时会把关联的MemoryStream也关闭,后续无法正常使用流。
  • 拼写错误:注释中的Bitmap.FormStream是笔误,正确写法是Bitmap.FromStream。

修正后的参考代码

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;
                using (PrincipalSearcher srch = new PrincipalSearcher(userPrincipal))
                {
                    using (UserPrincipal results = (UserPrincipal)srch.FindOne())
                    {
                        if (results == null)
                        {
                            ldapUser = null;
                            return ldapUser;
                        }
                        
                        ldapUser.Name = results.DisplayName;
                        ldapUser.EmailId = results.EmailAddress;
                        
                        DirectoryEntry directoryEntry = (DirectoryEntry)results.GetUnderlyingObject();
                        PropertyValueCollection collection = directoryEntry.Properties["thumbnailPhoto"];
                        if (collection.Value != null && collection.Value is byte[] thumbnailInBytes)
                        {
                            // 场景1:需要Bitmap对象(仅Windows环境)
                            // using (var ms = new MemoryStream(thumbnailInBytes))
                            // {
                            //     var bitmap = new Bitmap(ms);
                            //     // 后续处理bitmap的逻辑
                            // }
                            
                            // 场景2:直接存本地文件
                            // File.WriteAllBytes($"{ldapUser.EmailId}_avatar.jpg", thumbnailInBytes);
                            
                            // 场景3:Web接口直接返回
                            // 直接把thumbnailInBytes赋值给ldapUser的头像字节属性即可
                            ldapUser.AvatarBytes = thumbnailInBytes;
                        }
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        // 建议此处添加日志记录ex的具体信息,方便排查问题
        ldapUser = null;
    }
    return ldapUser;
}

内容的提问来源于stack exchange,提问作者Thejus32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 00:45:00