C# 试图使用C在Active Directory中创建用户帐户。出现无效的dn语法错误

C# 试图使用C在Active Directory中创建用户帐户。出现无效的dn语法错误,c#,active-directory,ldap,C#,Active Directory,Ldap,我正在尝试使用以下代码在Active directory中创建用户帐户。当我试图执行代码时,我得到一个无效的DN语法错误。我通过ADSI编辑工具和LDAP搜索工具检查了DN信息,它与我在代码中输入的内容相匹配。我尝试了各种登录,但仍然失败。我的代码如下。关于域名和登录名的一些信息已经为这篇文章修改。任何帮助都将不胜感激 using System; using System.Collections.Generic; using System.Linq; using System.Text; usi

我正在尝试使用以下代码在Active directory中创建用户帐户。当我试图执行代码时,我得到一个无效的DN语法错误。我通过ADSI编辑工具和LDAP搜索工具检查了DN信息,它与我在代码中输入的内容相匹配。我尝试了各种登录,但仍然失败。我的代码如下。关于域名和登录名的一些信息已经为这篇文章修改。任何帮助都将不胜感激

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.DirectoryServices;
using System.DirectoryServices.Protocols;
using System.DirectoryServices.AccountManagement;
using System.DirectoryServices.ActiveDirectory;

namespace NewAccount
{
class Program
{
    public struct UserInfo
    {
        public string username;
        public string sAMAccountName;
        public string firstName;
        public string lastName;
        public string displayName;
        public string emailAddress;


    }
    static void Main(string[] args)
    {

        UserInfo newUserinfo;
        newUserinfo.firstName = "Tom";
        newUserinfo.lastName = "Pig";
        newUserinfo.displayName = "Tom Pig";
        newUserinfo.emailAddress = "Tompig@domain.k12.or.us";
        newUserinfo.username = "TomPig";
        newUserinfo.sAMAccountName = "tompig";

        string path = "LDAP://CN=Users,DC=domain,DC=k12,DC=or,DC=us";
        DirectoryEntry adUserFolder = new DirectoryEntry(path,"admin","pass",AuthenticationTypes.Secure);

        DirectoryEntry newUser = adUserFolder.Children.Add("CN" + newUserinfo.username, "User");

        newUser.Properties["sAMAccountName"].Value = newUserinfo.sAMAccountName;
        newUser.Properties["givenName"].Value = newUserinfo.firstName;
        newUser.Properties["sn"].Value = newUserinfo.lastName;
        newUser.Properties["displayName"].Value = newUserinfo.displayName;
        newUser.Properties["mail"].Value = newUserinfo.emailAddress;

        newUser.CommitChanges();


        newUser.Invoke("setpassword", "P@ssWord!");
        newUser.Properties["userAccountControl"].Value = 0x0200;
        newUser.CommitChanges();

        Console.WriteLine("User: " + newUserinfo.username + " successfully created!");
        Console.WriteLine("Hit any key to continue.");
        Console.ReadLine();
    }

}
}

我想你需要让这行有CN=:

DirectoryEntry newUser = adUserFolder.Children.Add("CN=" + newUserinfo.username, "User");