如何在Windows 7或Windows Server 2008上以编程方式创建Windows用户帐户?

我一直在尝试在Windows 7机器上创建新的本地用户帐户。 我使用了System.DirectoryServices.DirectoryEntry类(如此处所示 )但它似乎不起作用。

这是文章中的代码:

static void Main(string[] args) { try { DirectoryEntry AD = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"); DirectoryEntry NewUser = AD.Children.Add("TestUser1", "user"); NewUser.Invoke("SetPassword", new object[] {"#12345Abc"}); NewUser.Invoke("Put", new object[] {"Description", "Test User from .NET"}); NewUser.CommitChanges(); DirectoryEntry grp; grp = AD.Children.Find("Guests", "group"); if (grp != null) {grp.Invoke("Add", new object[] {NewUser.Path.ToString()});} Console.WriteLine("Account Created Successfully"); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message); Console.ReadLine(); } } 

执行此行时

DirectoryEntry NewUser = AD.Children.Add("TestUser1", "user");

我得到了

带有“ {"Unknown error (0x80005000)"} ”的System.Runtime.InteropServices.COMException

作为exception消息,并将-2147463168作为错误代码。

我认为这可能是因为该文章针对Windows XP及以下的机器,我的目标是Windows 7和Windows Server 2008。

任何帮助赞赏!

更新:
出于一些神秘的原因,我不再看到System.Runtime.InteropServices.COMException ,但是,当在newuser.CommitChanges()提交更改时,我得到一个“ UnAuthorizedAccessException ”。 我尝试以管理员身份运行该应用,但仍无法正常工作。

更新2:
好的,在更改为UserPrincipal类之后,我得到了以下代码:

 public UserPrincipal CreateNewUser(string sUserName, string sPassword) { // first check that the user doesn't exist if (GetUser(sUserName) == null) { PrincipalContext oPrincipalContext = GetPrincipalContext(); UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext); oUserPrincipal.Name = sUserName; oUserPrincipal.SetPassword(sPassword); //User Log on Name //oUserPrincipal.UserPrincipalName = sUserName; oUserPrincipal.Save(); return oUserPrincipal; } // if it already exists, return the old user return GetUser(sUserName); } } 

当我将其作为控制台应用程序运行时,此代码运行良好 – 当然以管理员身份运行 – 但是当我将其部署为Windows服务时,安全帐户设置为“LocalSystem”,我得到一个InvlaidOperationException说“底层存储不会支持这个属性“

思考?

好的,如果您检查我的上次更新,则以下代码段有效:

 public UserPrincipal CreateNewUser(string sUserName, string sPassword) { // first check that the user doesn't exist if (GetUser(sUserName) == null) { PrincipalContext oPrincipalContext = GetPrincipalContext(); UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext); oUserPrincipal.Name = sUserName; oUserPrincipal.SetPassword(sPassword); //User Log on Name //oUserPrincipal.UserPrincipalName = sUserName; oUserPrincipal.Save(); return oUserPrincipal; } // if it already exists, return the old user return GetUser(sUserName); } } 

这可以作为控制台应用程序,但由于部署为Windows服务时的安全性exception而无法执行。 一个解决方案是信任该程序集(Windows服务程序集),以便.net安全性允许它运行。 已经完成了,现在一切都很酷!

您需要在用户名前加上CN =,如下所示:

DirectoryEntry NewUser = AD.Children.Add("CN=TestUser1", "user");