create local user account

I had a very similar issue change the first line to

PrincipalContext context = new PrincipalContext(ContextType.Machine, "127.0.0.1");

see if that fixes your issue. And triple check that the program is running with administrator privileges.

The other issue it could be is the server has password complexity requirements and password that is being passed in to the function does not meet those requirements. Does the problem go away if you pass it ASfas123@!fda as the password?

I am 90% sure it is one of those two issues.


For your user groups not saving I am not sure why. Here is a snippit from one of my projects that is doing the same thing you are. I cant see the diffrence.

using (GroupPrincipal r = GroupPrincipal.FindByIdentity(context, "Remote Desktop Users"))
using (GroupPrincipal u = GroupPrincipal.FindByIdentity(context, "Users"))
{
    //snip
    UserPrincipal user = null;
    try
    {
        if (userInfo.NewPassword == null)
            throw new ArgumentNullException("userInfo.NewPassword", "userInfo.NewPassword was null");
        if (userInfo.NewPassword == "")
            throw new ArgumentOutOfRangeException("userInfo.NewPassword", "userInfo.NewPassword was empty");
        //If the user already is in the list of existing users use that one.
        if (pr.ContainsKey(username))
        {
            user = (UserPrincipal)pr[username];
            user.Enabled = true;
            user.SetPassword(userInfo.NewPassword);
        }
        else
        {
            //create new windows user.
            user = new UserPrincipal(context, username, userInfo.NewPassword, true);
            user.UserCannotChangePassword = true;
            user.PasswordNeverExpires = true;
            user.Save();
            r.Members.Add(user);
            r.Save();
            u.Members.Add(user);
            u.Save();
        }
        IADsTSUserEx iad = (IADsTSUserEx)((DirectoryEntry)user.GetUnderlyingObject()).NativeObject;
        iad.TerminalServicesInitialProgram = GenerateProgramString(infinityInfo);
        iad.TerminalServicesWorkDirectory = Service.Properties.Settings.Default.StartInPath;
        iad.ConnectClientDrivesAtLogon = 0;
        user.Save();              
    }
    catch(Exception e)
    {
       //snip
    }
    finally
    {
        if (user != null)
        {
            user.Dispose();
        }
    }
}

Leave a Comment