开发者

Access denied when trying to add Windows User account

I am trying to programmatically add a user like this below but get an access denied message on the Save. I'm running locally on Windows 7 and the code resides in a console app.

/// <summary>
/// 
/// </summary>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="description"></param>
public static void CreateUser(string userName, string password, string description)
{
    PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);
    System.DirectoryServices.Accoun开发者_JAVA百科tManagement.UserPrincipal u = new UserPrincipal(pc);
    u.SetPassword(password);
    u.Name = userName;
    u.Description = description;
    u.UserCannotChangePassword = true;
    u.PasswordNeverExpires = true;
    u.Save();

    GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, "Users");
    gp.Members.Add(u);
    gp.Save();
}

Any ideas? I tried supplying an administrators username and password and still get the same error.

The console app gets executed like this:

 ProcessStartInfo startInfo = new ProcessStartInfo();
                    startInfo.UserName = userName;
                    startInfo.Password = securePassword;
                    startInfo.LoadUserProfile = true;
                    startInfo.UseShellExecute = false;
                    startInfo.FileName = batchPath;
                    startInfo.Arguments = operationLogID.ToString();
                    Process.Start(startInfo);

Here is a rough view of how the code is set up:

  • Console App test harness gets executed in debug mode.
  • I check for a user and if they don't exist..then I try and create it shown above. This is where the error occurs.


Even if you're logged in as admin, you need to run your console as admin. Here's how to launch a console as admin: http://www.howtogeek.com/howto/windows-vista/run-a-command-as-administrator-from-the-windows-vista-run-box/.

Then find your console app and run it.

Good luck!

-Michael

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜