Start a new Process as another user

On my last post User Credentials CommandDialog with SecureString password I showed an example on how to get the user credentials using a standard windows dialog and spawn a new process with those credentials.

Now let’s assume that you want to get the output/input/errors of that process from the standard streams (that is an interprocess communication channel) and therefore you set the required redirects property. Let’s say that you want to get the output result from a process that executes a command line tool, so you will do something like this:

 

 

ProcessStartInfo info = new ProcessStartInfo("notepad.exe");

info.UseShellExecute = false;

info.RedirectStandardOutput = true;

 

 

The problem with the above code is that you need to redirect the three streams; otherwise you’ll receive an exception like this:

 

 

System.ComponentModel.Win32Exception: The handle is invalid.

 

 

So the code to start a new process with user credentials and standard stream redirection may look like this:

 

 

ProcessStartInfo info = new ProcessStartInfo("cmd.exe");

info.UseShellExecute = false;

info.RedirectStandardInput = true;

info.RedirectStandardError = true;

info.RedirectStandardOutput = true;

info.UserName = dialog.User; // see the link mentioned at the top

info.Password = dialog.Password;

using (Process install = Process.Start(info))

{

      string output = install.StandardOutput.ReadToEnd();

      install.WaitForExit();

      // Do something with you output data

      Console.WriteLine(output);

}

 

 

Note: The Three-Redirect requirement is valid whenever these two conditions are met:

 

1)    Starting a new process with a different account than the parent process.

2)    Your parent process is running inside a VS add-in or VS Test project.

 

If you want further information about these scenarios, you may find it here and here.

 

This is the technical explanation given in one of these reported bugs.

 

Specifying any one of
RedirectStandardOutput=true,
RedirectStandardError=true, or
RedirectStandardInput=true
causes the process to be launched with STARTF_USESTDHANDLES (See the Win32 API CreateProcessWithLogon). This flag applies to all three handles, whether they are specified or not. If your process does not have any of these handles, then CreateProcessWithLogon will fail with "Invalid Handle".

Console applications have StandardInput connected to the console keyboard by default. GUI processes do not have StandardInput handles by default, so you MUST redirect it (even if you don't intend to write anything to it).

  

This posting is provided "AS IS" with no warranties, and confers no rights. 

11 Comments

  • Great! Thanks for the information!

    Jack

  • Thanks, the tip to redirect all 3 streams was a real life saver.

  • thanks for your help
    i forgot to put RedirectStandardInput=true
    thanks

  • That was so excellent.

  • thanks a lot
    "If your process does not have any of these handles, then CreateProcessWithLogon will fail with "Invalid Handle"."

    It help me get out of the troble "invalid handle".(I forget to set the errPipe)

  • I was getting "The handle is invalid" error starting up a console routine from a Windows service. I found a bug report to Microsoft saying this message should be changed to something more suitable for diagnostics. Figuring out "what handle?!" was impossible. I found the advice you've provided here in a couple other places but it didn't sink in until I read your posting here a couple times. Thanks for the VERY helpful info.

  • Hi - I'm using your technique to automate a sharepoint install (running the install as an admin, then the PSCONFIG commands as the account w/ rights to the DB) and it works great except for one issue - I can't get the console windows to appear hidden or Minimized - is this an issue with the API wrapper?

    Chris

  • pr.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    pr.StartInfo.CreateNoWindow = true;

  • Hello.
    I'am try to use it in web-service but no luck. The process was not started.
    Did you know how can launch winform application from web-service under a specific user?

  • Startprocessasuser.. Smashing :)

  • Thx!!!!!

    I want to use "UserName" and "RedirectStandardOutput" at the same time, but Win32Exception welcomed me.

    When I corrected "startInfo.RedirectStandardOutput = true;" to

    "startInfo.RedirectStandardOutput = true;

    startInfo.RedirectStandardInput = true;

    startInfo.RedirectStandardError = true;" and it got solved~!

Comments have been disabled for this content.