我一直在尝试在 Windows 7 计算机上创建新的本地用户帐户。我使用了 System.DirectoryServices.DirectoryEntry 类(如here)但它似乎不起作用。
这是文章中的代码:
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");
I get a
System.Runtime.InteropServices.COMException
with "{"Unknown error (0x80005000)"}
"
作为异常消息,并且-2147463168
作为错误代码。
我认为这可能是因为本文针对的是 Windows XP 及更低版本的计算机,而我的目标是 Windows 7 和 Windows Server 2008。
任何帮助表示赞赏!
Update:
由于某种神秘的原因,我不再看到它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
说“底层商店不支持此属性”
想法?