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.
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.