Reputation: 935
I want to create a windows user using c# code. Below methods works fine when the logged in user is having Administratorive privilage. It is not working with the limited user. Note that I can pass the windows user name and password of the administrator user. Basically I want to impersonate. I tried impersonation it did not work. I tried passing user namd and password to the processinfo. I got the error "The stub received bad data". So can any one help me on how to create the windows user using c# code by impersonation.
public static void CreateUser(string userName, string password, string description, string adminUserName, string adminPassword)
{
Process process = new Process();
ProcessStartInfo processInfo = new ProcessStartInfo();
processInfo.WorkingDirectory = Environment.SystemDirectory;
processInfo.FileName = "net.exe";
processInfo.UseShellExecute = false;
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardInput = true;
processInfo.RedirectStandardOutput = true;
processInfo.WindowStyle = ProcessWindowStyle.Hidden;
processInfo.Arguments = @" user " + userName + @" " + password + @" /ADD /ACTIVE:YES " +
@"/EXPIRES:NEVER /FULLNAME:" + userName + @" /PASSWORDCHG:NO /PASSWORDREQ:YES";
if (!string.IsNullOrEmpty(adminUserName))
{
processInfo.UserName = adminUserName;
processInfo.Password = WindowsSecurityHelper.GetSecuredString(adminPassword);
}
process.StartInfo = processInfo;
process.Start();
process.WaitForExit();
process.Close();
}
or
public static void CreateUser(string userName, string password, string description, string userGroup = "Users")
{
PrincipalContext pc = new PrincipalContext(ContextType.Machine, null);
GroupPrincipal gp = GroupPrincipal.FindByIdentity(pc, userGroup);
if (gp != null)
{
UserPrincipal u = new UserPrincipal(pc);
u.SetPassword(password);
u.Name = userName;
u.Description = description;
u.UserCannotChangePassword = true;
u.PasswordNeverExpires = true;
u.Save();
gp.Members.Add(u);
gp.Save();
}
}
Upvotes: 3
Views: 2243
Reputation: 618
I had the same error and found that I needed to specify the Domain parameter in the ProcessStartInfo.
Upvotes: 0
Reputation: 499152
You can use the Process
class with different credentials - instead of setting it directly, use ProcessStartInfo
.
You can set a UserName
and Password
on the ProcessStartInfo
class for the user you wish to execute as (Password
is a SecureString
, by the way) - pass this to the Process
constructor and you are good to go.
ProcessStartInfo startInfo = new ProcessStartInfo("net.exe");
startInfo.UserName = Administrator;
startInfo.Password = ...;
...
Process.Start(startInfo);
Upvotes: 3