赞
踩
- private void AddADUser(Workbook workbook)
- {
- try
- {
- // 使用PrincipalContext来进行身份验证
- using (PrincipalContext context = new PrincipalContext(ContextType.Domain, domain))
- {
- Worksheet sheet = workbook.Worksheets["用户信息"];
- int rowCount = sheet.Rows.Length;
- if (rowCount < 2)
- {
- textBox1.Text += "EXCEL的用户页为空。\r\n";
- return;
- }
- for (int row = 2; row <= rowCount; row++) // Assuming the first row is for headers
- {
- string firstNm = sheet.Range[row, 1].Value.Trim(); //姓
- string sndNm = sheet.Range[row, 2].Value;//名
- string acountNm = sheet.Range[row, 3].Value;//acountNm
- string password = sheet.Range[row, 4].Value;//密码
- string OU = sheet.Range[row, 5].Value;//OU
- if (string.IsNullOrEmpty(firstNm) || string.IsNullOrEmpty(acountNm) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(OU))
- {
- textBox1.Text += "请检查第 " + row + "行是否有空值\r\n";
- }
- else
- {
- string userName = acountNm;
- if (UserExists(context, userName))
- {
- textBox1.Text += "用户已存在:" + userName + "\r\n";
- }
- else
- {
- // 新建用户
- string orgPath = "LDAP://" + OU + ",DC=****,DC=net,DC=cn";
- DirectoryEntry ou = new DirectoryEntry(orgPath);
- DirectoryEntry newUser = ou.Children.Add("CN=" + firstNm + sndNm, "user");
- newUser.Properties["samAccountName"].Value = acountNm;
- newUser.Properties["sn"].Value = firstNm;//姓https://www.cnblogs.com/CSharpDevelopers/p/3634635.html
- if (!String.IsNullOrEmpty(sndNm))
- {
- newUser.Properties["givenName"].Value = sndNm;
- }
- newUser.Properties["userPrincipalName"].Value = acountNm + "@****.net.cn";//用户登录名
- newUser.Properties["name"].Value = firstNm + sndNm;
- newUser.CommitChanges();
-
- // 设置密码
- try
- {
- Object[] newPassword = new Object[] { password };
- newUser.Invoke("SetPassword", newPassword);
- newUser.Properties["userAccountControl"].Value = 0x200; // 设置用户为启用状态
- newUser.CommitChanges();
- textBox1.Text += "已创建用户:" + acountNm + "\r\n";
- }
- catch (Exception ex)
- {
- // 处理设置密码时的异常
- textBox1.Text += "创建用户失败:" + ex.Message + "\r\n";
- }
- }
- }
- }
- }
- }
- catch (Exception ex)
- {
- textBox1.Text += "添加域用户失败,可能的原因是:" + ex.Message;
- }
- }
- private bool UserExists(PrincipalContext context, string userName)
- {
- UserPrincipal user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, userName);
- return user != null;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。