使用C#创建AD用户时无法指定正确OU的问题
解决C#创建AD用户无法指定OU的问题
你的核心问题是:创建了目标OU的DirectoryEntry,但完全没把它和UserPrincipal关联起来,UserPrincipal默认会使用PrincipalContext的默认容器(也就是域的Users OU)保存用户,所以不管你写了多么正确的OU路径,都不会生效。
修复方案一(基于UserPrincipal)
修改代码,在保存用户时指定目标OU作为父容器:
string ouPath = $"OU=Users,OU={selectedDepartment},OU={selectedLocation},DC=vollmer,DC=lan"; string fullPath = $"LDAP://{ouPath}"; using (DirectoryEntry ouEntry = new DirectoryEntry(fullPath)) { // 将目标OU转换为Principal对象 using (Principal ouPrincipal = Principal.FindByIdentity(context, IdentityType.DistinguishedName, ouPath)) { using (UserPrincipal newUser = new UserPrincipal(context)) { newUser.SamAccountName = username; newUser.GivenName = firstName; newUser.Surname = lastName; newUser.SetPassword(password); newUser.Enabled = true; // 关键:保存到指定OU newUser.Save(ouPrincipal); } } }
修复方案二(基于DirectoryEntry直接创建)
绕开Principal类,直接通过DirectoryEntry在目标OU下创建用户,逻辑更直观:
string ouPath = $"OU=Users,OU={selectedDepartment},OU={selectedLocation},DC=vollmer,DC=lan"; string fullPath = $"LDAP://{ouPath}"; using (DirectoryEntry ouEntry = new DirectoryEntry(fullPath)) { // 在目标OU下添加用户条目 DirectoryEntry newUserEntry = ouEntry.Children.Add($"CN={firstName} {lastName}", "user"); // 设置用户属性 newUserEntry.Properties["sAMAccountName"].Value = username; newUserEntry.Properties["givenName"].Value = firstName; newUserEntry.Properties["sn"].Value = lastName; // 设置密码(注意:若未启用SSL,需确保域控制器允许明文密码传输) newUserEntry.Invoke("SetPassword", password); // 启用账户(512代表NORMAL_ACCOUNT,启用状态) newUserEntry.Properties["userAccountControl"].Value = 512; // 提交所有修改 newUserEntry.CommitChanges(); }
额外注意事项
- 确认运行代码的账号拥有目标OU的用户创建权限
- 检查OU的DistinguishedName是否完全正确(比如你调试时写的是
DC=company,但代码里是DC=vollmer,要保证和实际域一致) - 若使用Principal方式,确保
context(PrincipalContext)的域配置正确
内容的提问来源于stack exchange,提问作者Sabi
相关产品推荐
相关产品推荐

