本文介绍了在 .NET (C#) 中创建 Active Directory 用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 Active Directory 中创建一个新用户.我发现了几个类似如下的例子:

I need to create a new user in Active Directory. I have found several examples like the following:

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);
         }
      }
   }
}

当我运行此代码时,我没有收到任何错误,但没有创建新用户.

When I run this code I get no errors, but no new user is created.

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

The account I'm running the test with has sufficient privileges to create a user in the target Organizational Unit.

我是否遗漏了什么(可能是用户对象的某些必需属性)?

Am I missing something (possibly some required attribute of the user object)?

为什么代码不给出异常的任何想法?

Any ideas why the code does not give exceptions?

编辑
以下对我有用:

EDIT
The following worked for me:

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();

所以实际上有几个问题:

So there were actually a couple of problems:

  1. CommitChanges 必须在 user 上调用(感谢 Rob)
  2. 密码策略阻止创建用户(感谢 Marc)
  1. CommitChanges must be called on user (thanks Rob)
  2. The password policy was preventing the user to be created (thanks Marc)

推荐答案

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

I think you are calling CommitChanges on the wrong DirectoryEntry. In the MSDN documentation (http://msdn.microsoft.com/en-us/library/system.directoryservices.directoryentries.add.aspx) it states the following (emphasis added by me)

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

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

So if you change your code to user.CommitChanges() it should work, if you need to set more properties than just the account name then you should get an exception.

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

Since you're currently calling CommitChanges() on the OU which hasn't been altered there will be no exceptions.

这篇关于在 .NET (C#) 中创建 Active Directory 用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-08 09:02