用C#对Active Directory进行增删修查
1 第一个类,获取AD实例类; 2 3 AdHerlp.cs 4 5 public static class AdHerlp 6 { 7 #region 创建AD连接 8 /// <summary> 9 /// 创建AD连接 10 /// </summary> 11 /// <returns></returns> 12 public static DirectoryEntry GetDirectoryEntry() 13 { 14 DirectoryEntry de = new DirectoryEntry(); 15 de.Path = "LDAP://qjyczsgl/CN=Users,DC=qjyczsgl,DC=com"; 16 de.Username = @"qjyczsgl\zsgl"; 17 de.Password = "qjyczsgl"; 18 return de; 19 } 20 #endregion 21 22 #region 获取目录实体集合 23 /// <summary> 24 /// 25 /// </summary> 26 /// <param name="DomainReference"></param> 27 /// <returns></returns> 28 public static DirectoryEntry GetDirectoryEntry(string DomainReference) 29 { 30 DirectoryEntry entry = new DirectoryEntry("LDAP://qjyczsgl" + DomainReference, "zsgl", "qjyczsgl", AuthenticationTypes.Secure); 31 return entry; 32 } 33 #endregion 34 } 35 36 AD操作类 37 38 myDirectory.cs 39 40 class myDirectory 41 { 42 43 /// <summary> 44 /// 判断用户是否存在 45 /// </summary> 46 /// <param name="UserName"></param> 47 /// <returns></returns> 48 public bool UserExists(string UserName) 49 { 50 DirectoryEntry de = AdHerlp.GetDirectoryEntry(); 51 DirectorySearcher deSearch = new DirectorySearcher(); 52 deSearch.SearchRoot = de; 53 deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))"; 54 SearchResultCollection results = deSearch.FindAll(); 55 if (results.Count == 0) 56 { 57 return false; 58 } 59 else 60 { 61 return true; 62 } 63 } 64 /// <summary> 65 /// 修改用户属性 66 /// </summary> 67 /// <param name="de"></param> 68 /// <param name="PropertyName"></param> 69 /// <param name="PropertyValue"></param> 70 public static void SetProperty(DirectoryEntry de, string PropertyName, string PropertyValue) 71 { 72 if (PropertyValue != null) 73 { 74 if (de.Properties.Contains(PropertyName)) 75 { 76 de.Properties[PropertyName][0] = PropertyValue; 77 } 78 else 79 { 80 de.Properties[PropertyName].Add(PropertyValue); 81 } 82 } 83 } 84 85 /// <summary> 86 /// 生成随机密码 87 /// </summary> 88 /// <returns></returns> 89 public string SetSecurePassword() 90 { 91 //RandomPassword rp = new RandomPassword(); 92 return RandomPassword.Generate(8, 8); 93 } 94 95 /// <summary> 96 /// 设置用户新密码 97 /// </summary> 98 /// <param name="path"></param> 99 public void SetPassword(string path) 100 { 101 DirectoryEntry usr = new DirectoryEntry(); 102 usr.Path = path; 103 usr.AuthenticationType = AuthenticationTypes.Secure; 104 object[] password = new object[] { SetSecurePassword() }; 105 object ret = usr.Invoke("SetPassword", password); 106 usr.CommitChanges(); 107 usr.Close(); 108 } 109 110 /// <summary> 111 /// 启用用户帐号 112 /// </summary> 113 /// <param name="de"></param> 114 private static void EnableAccount(DirectoryEntry de) 115 { 116 //UF_DONT_EXPIRE_PASSWD 0x10000 117 int exp = (int)de.Properties["userAccountControl"].Value; 118 de.Properties["userAccountControl"].Value = exp | 0x0001; 119 de.CommitChanges(); 120 //UF_ACCOUNTDISABLE 0x0002 121 int val = (int)de.Properties["userAccountControl"].Value; 122 de.Properties["userAccountControl"].Value = val & ~0x0002; 123 de.CommitChanges(); 124 } 125 126 /// <summary> 127 /// 添加用户到组 128 /// </summary> 129 /// <param name="de"></param> 130 /// <param name="deUser"></param> 131 /// <param name="GroupName"></param> 132 public static void AddUserToGroup(DirectoryEntry de, DirectoryEntry deUser, string GroupName) 133 { 134 DirectorySearcher deSearch = new DirectorySearcher(); 135 deSearch.SearchRoot = de; 136 deSearch.Filter = "(&(objectClass=group) (cn=" + GroupName + "))"; 137 SearchResultCollection results = deSearch.FindAll(); 138 139 bool isGroupMember = false; 140 141 if (results.Count > 0) 142 { 143 DirectoryEntry group = AdHerlp.GetDirectoryEntry(results[0].Path); 144 145 object members = group.Invoke("Members", null); 146 foreach (object member in (IEnumerable)members) 147 { 148 DirectoryEntry x = new DirectoryEntry(member); 149 if (x.Name != deUser.Name) 150 { 151 isGroupMember = false; 152 } 153 else 154 { 155 isGroupMember = true; 156 break; 157 } 158 } 159 160 if (!isGroupMember) 161 { 162 group.Invoke("Add", new object[] { deUser.Path.ToString() }); 163 } 164 group.Close(); 165 } 166 return; 167 } 168 169 /// <summary> 170 /// 创建一个新用户 171 /// </summary> 172 /// <param name="employeeID"></param> 173 /// <param name="name"></param> 174 /// <param name="login"></param> 175 /// <param name="email"></param> 176 /// <param name="group"></param> 177 public void CreateNewUser(string employeeID, string name, string login, string email, string group) 178 { 179 //Catalog catalog = new Catalog(); 180 DirectoryEntry de =AdHerlp.GetDirectoryEntry(); 181 182 /// 1. Create user account 183 DirectoryEntries users = de.Children; 184 DirectoryEntry newuser = users.Add("CN=" + login, "user"); 185 186 /// 2. Set properties 187 SetProperty(newuser, "employeeID", employeeID); 188 SetProperty(newuser, "givenname", name); 189 SetProperty(newuser, "SAMAccountName", login); 190 SetProperty(newuser, "userPrincipalName", login); 191 SetProperty(newuser, "mail", email); 192 newuser.CommitChanges(); 193 194 /// 3. Set password 195 SetPassword(newuser.Path); 196 newuser.CommitChanges(); 197 198 /// 4. Enable account 199 EnableAccount(newuser); 200 201 /// 5. Add user account to groups 202 AddUserToGroup(de, newuser, group); 203 204 /// 6. Create a mailbox in Microsoft Exchange 205 //GenerateMailBox(login); 206 207 newuser.Close(); 208 de.Close(); 209 } 210 /// <summary> 211 /// 禁用一个帐号 212 /// </summary> 213 /// <param name="EmployeeID"></param> 214 public void DisableAccount(string EmployeeID) 215 { 216 DirectoryEntry de =AdHerlp.GetDirectoryEntry(); 217 DirectorySearcher ds = new DirectorySearcher(de); 218 ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + EmployeeID + "))"; 219 ds.SearchScope = SearchScope.Subtree; 220 SearchResult results = ds.FindOne(); 221 222 if (results != null) 223 { 224 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path); 225 int val = (int)dey.Properties["userAccountControl"].Value; 226 dey.Properties["userAccountControl"].Value = val | 0x0002; 227 dey.Properties["msExchHideFromAddressLists"].Value = "TRUE"; 228 dey.CommitChanges(); 229 dey.Close(); 230 } 231 232 de.Close(); 233 } 234 /// <summary> 235 /// 修改用户信息 236 /// </summary> 237 /// <param name="employeeID"></param> 238 /// <param name="department"></param> 239 /// <param name="title"></param> 240 /// <param name="company"></param> 241 public void ModifyUser(string employeeID, string department, string title, string company) 242 { 243 DirectoryEntry de = AdHerlp.GetDirectoryEntry(); 244 DirectorySearcher ds = new DirectorySearcher(de); 245 ds.Filter = "(&(objectCategory=Person)(objectClass=user)(employeeID=" + employeeID + "))"; 246 ds.SearchScope = SearchScope.Subtree; 247 SearchResult results = ds.FindOne(); 248 249 if (results != null) 250 { 251 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(results.Path); 252 SetProperty(dey, "department", department); 253 SetProperty(dey, "title", title); 254 SetProperty(dey, "company", company); 255 dey.CommitChanges(); 256 dey.Close(); 257 } 258 259 de.Close(); 260 } 261 262 /// <summary> 263 /// 检验Email格式是否正确 264 /// </summary> 265 /// <param name="mail"></param> 266 /// <returns></returns> 267 public bool IsEmail(string mail) 268 { 269 Regex mailPattern = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); 270 return mailPattern.IsMatch(mail); 271 } 272 /// <summary> 273 /// 搜索被修改过的用户 274 /// </summary> 275 /// <param name="fromdate"></param> 276 /// <returns></returns> 277 public DataTable GetModifiedUsers(DateTime fromdate) 278 { 279 DataTable dt = new DataTable(); 280 dt.Columns.Add("EmployeeID"); 281 dt.Columns.Add("Name"); 282 dt.Columns.Add("Email"); 283 284 DirectoryEntry de = AdHerlp.GetDirectoryEntry(); 285 DirectorySearcher ds = new DirectorySearcher(de); 286 287 StringBuilder filter = new StringBuilder(); 288 filter.Append("(&(objectCategory=Person)(objectClass=user)(whenChanged>="); 289 filter.Append(ToADDateString(fromdate)); 290 filter.Append("))"); 291 292 ds.Filter = filter.ToString(); 293 ds.SearchScope = SearchScope.Subtree; 294 SearchResultCollection results = ds.FindAll(); 295 296 foreach (SearchResult result in results) 297 { 298 DataRow dr = dt.NewRow(); 299 DirectoryEntry dey = AdHerlp.GetDirectoryEntry(result.Path); 300 dr["EmployeeID"] = dey.Properties["employeeID"].Value; 301 dr["Name"] = dey.Properties["givenname"].Value; 302 dr["Email"] = dey.Properties["mail"].Value; 303 dt.Rows.Add(dr); 304 dey.Close(); 305 } 306 307 de.Close(); 308 return dt; 309 } 310 311 /// <summary> 312 /// 格式化AD的时间 313 /// </summary> 314 /// <param name="date"></param> 315 /// <returns></returns> 316 public string ToADDateString(DateTime date) 317 { 318 string year = date.Year.ToString(); 319 int month = date.Month; 320 int day = date.Day; 321 322 StringBuilder sb = new StringBuilder(); 323 sb.Append(year); 324 if (month < 10) 325 { 326 sb.Append("0"); 327 } 328 sb.Append(month.ToString()); 329 if (day < 10) 330 { 331 sb.Append("0"); 332 } 333 sb.Append(day.ToString()); 334 sb.Append("000000.0Z"); 335 return sb.ToString(); 336 } 337 }
相关的资料
C# AD(Active Directory)域信息同步,组织单位、用户等信息查询
http://www.cnblogs.com/zhongweiv/archive/2013/01/05/ad_sync.html
[C#]LDAP验证用户名和密码
http://blog.sina.com.cn/s/blog_6c762bb301010abp.html
Querying Adctive Directory with LDAP in C#
http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/729d1214-37f5-4330-9208-bc4d9d695ad0
C#获取AD用户信息
http://www.cnblogs.com/py891021/archive/2009/09/24/1573093.html
用C#对Active Directory进行增删修查的类源码
http://blog.sina.com.cn/s/blog_53864cba0100i4rz.html
(证实可用)C#获取AD所有的用户信息,比如登录名,邮件名,属于组织,名字
http://blog.csdn.net/blueseawindow/article/details/6092345
在AD中存取照片
http://www.cnblogs.com/xuanye/archive/2008/05/13/1195225.html
C# Datagirdview 用法集
http://blog.csdn.net/chend926/article/details/6941177
突破AD查询1000条限制
http://blog.csdn.net/foxbryant/article/details/7521958
AD中用户帐户属性userAccountControl
http://blog.csdn.net/xjzdr/article/details/3553246
如何察看windows 的SID
http://myocode.blog.51cto.com/blog/703470/505476
用户组类型
http://stackoverflow.com/questions/3554773/how-to-determine-whether-a-group-is-security-group
C# winform皮肤控件的破解与使用
http://hi.baidu.com/lost2happy/item/d1976acbcc869409ad092f93
posted on 2013-05-17 09:25 peter.peng 阅读(572) 评论(1) 编辑 收藏 举报