Ber*_*ord 2 c# active-directory
我正在创建一个应用程序 (.Net 3.5) 以允许用户在 Active Directory 中更新他们自己的照片和电话号码。
我正在使用 UserPrincipal 类,我已使用此示例对其进行了扩展
// Create the "thumbnailPhoto" property.
[DirectoryProperty("thumbnailPhoto")]
public byte[] thumbnailPhoto
{
get
{
if (ExtensionGet("thumbnailPhoto").Length != 1)
return null;
return (byte[])ExtensionGet("thumbnailPhoto")[0];
}
set
{
ExtensionSet("thumbnailPhoto", value);
}
}
Run Code Online (Sandbox Code Playgroud)
我得到字节数组并将其写入一个图片框
pictureBoxthumbnail.Image = Image.FromStream(new MemoryStream(userPrincipal.thumbnailPhoto));
Run Code Online (Sandbox Code Playgroud)
这显示了表格上的图片,到目前为止还不错。当我尝试将图像写入 Active Directory 时,我将图片框转换为字节数组
userPrincipal.thumbnailPhoto = ImageManipulation.imageToByteArray(pictureBoxthumbnail.Image);
public static byte[] imageToByteArray(System.Drawing.Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
Run Code Online (Sandbox Code Playgroud)
并尝试保存数据,但出现以下异常。
System.DirectoryServices.AccountManagement.PrincipalOperationException 未处理
消息=未指定的错误
来源=System.DirectoryServices.AccountManagement
错误代码=-2147467259
我怀疑我的图片框到字节数组是错误的。有人可以帮忙吗?
谢谢你。
我今天设法使用下面的功能让它工作。希望这对其他人有帮助。
private void UpdatePhoto()
{
var principalContext = new PrincipalContext(ContextType.Domain);
var userPrincipal = UserPrincipalEx.FindByIdentity(principalContext, System.Environment.UserName);
DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("LDAP://{0}:389/{1}", principalContext.ConnectedServer, userPrincipal.DistinguishedName));
directoryEntry.Properties["thumbnailPhoto"].Value = ImageManipulation.imageToByteArray(pictureBoxthumbnail.Image);
directoryEntry.CommitChanges();
}
Run Code Online (Sandbox Code Playgroud)