【发布时间】:2011-05-12 21:19:07
【问题描述】:
我一直在尝试在 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");
我得到一个
System.Runtime.InteropServices.COMException 与“{"Unknown error (0x80005000)"}”
作为异常消息,-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 说“底层存储不支持此属性”
想法?
【问题讨论】:
-
您是否运行了提升的应用程序?
-
您的意思是“作为管理员”?是的。同样的错误。
-
该错误实际上意味着“指定的目录服务属性或值不存在”。这种解释是否有帮助是另一回事。
-
Update 2 对没有丢失代码的旅友没有多大用处,我认为它可能来自这里 stackoverflow.com/questions/4199667/…