How to programmatically create Windows user accounts on Windows 7 or Windows Server 2008?

OK, if you check my last update, the following snippet worked:

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);
        }
    }

That worked as a console app, but failed to execute due to security exceptions when deployed as a windows service. A solution is to trust that assembly (the windows service assembly) so that the .net security will let it run. That's done, now everything is cool!

Tags:

C#

Windows 7