<form id="form1" runat="server"> <div> <asp:FileUpload ID="FileUploadPhoto" runat="server" /> <asp:Button ID="UploadPhoto" runat="server" Text="上传" OnClick="UploadPhoto_Click" /> </div> </form>
protected void UploadPhoto_Click(object sender, EventArgs e) { string name = FileUploadPhoto.PostedFile.FileName; string type = name.Substring(name.LastIndexOf(".")+1); //FileStream fs = File.OpenRead(name); byte[] content = new byte[FileUploadPhoto.PostedFile.ContentLength]; //fs.Read(content,0,content.Length); //fs.Close(); Stream fileStream = FileUploadPhoto.PostedFile.InputStream; fileStream.Read(content, 0, FileUploadPhoto.PostedFile.ContentLength); fileStream.Close(); ChangeADAccount("刘科","liuke",content); } /// <summary> /// 获得DirectoryEntry对象实例,以管理员登陆AD /// </summary> /// <returns></returns> private static DirectoryEntry GetDirectoryObject() { DirectoryEntry entry = null; try { entry = new DirectoryEntry("LDAP://10.10.10.1/DC=aaa,DC=com", "账户", "密码", AuthenticationTypes.Secure); } catch (Exception ex) { Debug.WriteLine(ex.Message); } return entry; } /// <summary> /// 根据用户公共名称取得用户的 对象 /// </summary> /// <param name="commonName">用户公共名称</param> /// <returns>如果找到该用户则返回用户的对象,否则返回 null</returns> public static DirectoryEntry GetDirectoryEntry(string commonName) { DirectoryEntry de = GetDirectoryObject(); DirectorySearcher deSearch = new DirectorySearcher(de); deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName.Replace("\\", "") + "))"; deSearch.SearchScope = SearchScope.Subtree; try { SearchResult result = deSearch.FindOne(); de = new DirectoryEntry(result.Path); return de; } catch (Exception ex) { Debug.WriteLine(ex.Message); return null; } } /// <summary> /// 设置指定的属性值 /// </summary> /// <param name="de"></param> /// <param name="propertyName">属性名称?</param> /// <param name="propertyValue">属性值</param> public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue) { if (de.Properties.Contains(propertyName)) { if (String.IsNullOrEmpty(propertyValue)) { de.Properties[propertyName].RemoveAt(0); } else { de.Properties[propertyName][0] = propertyValue; } } else { if (!String.IsNullOrEmpty(propertyValue)) { de.Properties[propertyName].Add(propertyValue); } } } /// <summary> /// 修改查询到的用户的图像 /// </summary> public static string ChangeADAccount(string CommonName, string Account, byte[] binaryData) { //获取对应AD实体 DirectoryEntry user = GetDirectoryEntry(CommonName); try { //SetProperty(user, " sAMAccountName ", Account); //user.Invoke("SetPhoto", new object[] { photo }); user.Properties["thumbnailPhoto"].Add(binaryData); user.CommitChanges(); } catch (Exception e) { Debug.WriteLine(e.Message); throw e; } return user.Path; }
然后在AD的 属性编辑器 选项卡看到 thumbnailPhoto 属性 有一堆二进制内容,即为上传成功的图片内容。
如果看不到此属性,点击筛选器,去掉 只显示有值的属性的勾。
解决文件名中文乱码
http://blog.csdn.net/lzy_1515/article/details/5538664
C#图片上传获取二进制流保存至AD,布布扣,bubuko.com
原文:http://www.cnblogs.com/kennyliu/p/3664145.html