在.NET中创建Active Directory用户(C#)

我需要在Active Directory中创建一个新用户。 我找到了几个例子如下:

using System; using System.DirectoryServices; namespace test { class Program { static void Main(string[] args) { try { string path = "LDAP://OU=x,DC=y,DC=com"; string username = "johndoe"; using (DirectoryEntry ou = new DirectoryEntry(path)) { DirectoryEntry user = ou.Children.Add("CN=" + username, "user"); user.Properties["sAMAccountName"].Add(username); ou.CommitChanges(); } } catch (Exception exc) { Console.WriteLine(exc.Message); } } } } 

当我运行此代码时,我没有错误,但没有创建新用户。

我正在运行测试的帐户具有足够的权限来在目标组织单位中创建用户。

我错过了什么(可能是用户对象的一些必需属性)?

任何想法为什么代码不给出例外?

编辑
以下对我有用:

 int NORMAL_ACCOUNT = 0x200; int PWD_NOTREQD = 0x20; DirectoryEntry user = ou.Children.Add("CN=" + username, "user"); user.Properties["sAMAccountName"].Value = username; user.Properties["userAccountControl"].Value = NORMAL_ACCOUNT | PWD_NOTREQD; user.CommitChanges(); 

所以实际上有几个问题:

  1. 必须在user上调用CommitChanges (感谢Rob)
  2. 密码策略阻止创建用户(感谢Marc)

我认为你在错误的DirectoryEntry上调用CommitChanges。 在MSDN文档( http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentries.add.aspx )中,它说明了以下内容(重点由我添加)

您必须在新条目上调用CommitChanges方法以使创建成为永久性。 调用此方法时,可以在新条目上设置强制属性值。 对于在调用CommitChanges方法之前需要设置的属性,每个提供程序都有不同的要求。 如果不满足这些要求,提供程序可能会抛出exception。 请咨询您的提供商,以确定在提交更改之前必须设置哪些属性。

因此,如果您将代码更改为user.CommitChanges(),它应该可以工作,如果您需要设置更多属性而不仅仅是帐户名,那么您应该得到一个例外。

由于您当前正在调用尚未更改的OU上的CommitChanges(),因此不会有例外。

假设您的OU路径OU=x,DC=y,DC=com确实存在 – 它应该工作:-)

要检查的事项:

  • 你正在为“samAccountName”添加一个值 – 为什么不设置它的值:

     user.Properties["sAMAccountName"].Value = username; 

否则你可能会得到几个samAccountNames – 这将无法正常工作…..

  • 你没有将userAccountControl属性设置为任何东西 – 尝试使用:

      user.Properties["userAccountControl"].Value = 512; // normal account 
  • 你的组织中有多个域控制器吗? 如果您,并且您正在使用此“无服务器”绑定(未在LDAP路径中指定任何服务器),您可能会惊讶于创建用户的位置:-)并且它需要几分钟到半小时在整个网络中同步

  • 你有严格的密码政策吗? 也许这就是问题所在。 我记得我们以前必须首先使用“不需要密码”选项创建用户,首先执行.CommitChanges(),然后创建足够强大的密码,在用户上设置它,并删除该用户选项。

检查以下代码

  DirectoryEntry ouEntry = new DirectoryEntry("LDAP://OU=TestOU,DC=TestDomain,DC=local"); for (int i = 3; i < 6; i++) { try { DirectoryEntry childEntry = ouEntry.Children.Add("CN=TestUser" + i, "user"); childEntry.CommitChanges(); ouEntry.CommitChanges(); childEntry.Invoke("SetPassword", new object[] { "password" }); childEntry.CommitChanges(); } catch (Exception ex) { } }