在C#中创建AD用户



我正试图使用C#创建一个AD,每次都会出现这个错误

System.DirectoryServices.DirectoryServicesOMException:'指定的目录服务属性或值不存在。

我似乎不明白为什么我会得到这个

private void ccNewHire_Button_Click(object sender, EventArgs e)
{
new Thread(() =>
{
String Password = passwordLabel.Text;
String First = newHireFirstName_TextBox.Text;
String Last = newHireLastName_TextBox.Text;
String Cnname = newHireFirstName_TextBox.Text + " " + newHireLastName_TextBox.Text;
String Username = newHireFirstName_TextBox.Text + "." + newHireLastName_TextBox.Text;
String Ldap = PathtoOURedacted;

DirectoryEntry newUser = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry childEntry = newUser.Children.Add("CN=" + Cnname, "user");
newUser.Properties["sAMAccountName"].Value = Username;
newUser.Properties["givenName"].Value = First;  // first name
newUser.Properties["sn"].Value = Last;    // surname = last name
newUser.Properties["displayName"].Value = Cnname;
newUser.Properties["password"].Value = Password;
newUser.Properties["userAccountControl"].Value = 512;
newUser.CommitChanges();

}).Start();
}

这是您的问题:

DirectoryEntry newUser = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry childEntry = newUser.Children.Add("CN=" + Cnname, "user");

您调用的是变量newUser,但将其设置为OU。因此,您最终会更改OU上的属性,而不是实际的新用户对象上的属性。只需重命名这些变量:

DirectoryEntry ou = new DirectoryEntry("LDAP://PathtoOURedacted");
DirectoryEntry newUser = ou.Children.Add("CN=" + Cnname, "user");

此外,这也不起作用:

newUser.Properties["password"].Value = Password;

密码属性是unicodePwd,但必须以文档中描述的非常特定的方式进行设置。在C#中,它看起来像这样:

newUser.Properties["unicodePwd"].Value = Encoding.Unicode.GetBytes($""{Password}"");

相关内容

  • 没有找到相关文章

最新更新