我一直在尝试在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();
}
}
Run Code Online (Sandbox Code Playgroud)
执行此行时
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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我将其作为控制台应用程序运行时,此代码运行良好 - 当然以管理员身份运行 - 但是当我将其部署为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);
}
}
Run Code Online (Sandbox Code Playgroud)
这可以作为控制台应用程序,但由于部署为Windows服务时的安全性异常而无法执行.解决方案是信任该程序集(Windows服务程序集),以便.net安全性允许它运行.已经完成了,现在一切都很酷!
| 归档时间: |
|
| 查看次数: |
23979 次 |
| 最近记录: |