.NET Process Start Process Error using credentials (The handle is invalid)
Asked Answered
V

1

9

I have an Windows Form application that supplies the User Name, Domain, and Password to the StartInfo, and it throws this:

System.ComponentModel.Win32Exception: The handle is invalid at System.Diagnostics.Process.StartWithCreateProcess(ProcessStartInfo startInfo) at System.Diagnostics.Process.Start()

When I allow the credentials to default to current user I get no such error, and the process I start works to the extent that it doesn't need to use credentials (the creds are necessary for mapping a drive in an MSBuild script). Here's the code that fills the start info:

Process p = new Process();
ProcessStartInfo si = new ProcessStartInfo(buildApp, buildArgs);
si.WorkingDirectory = msBuildWorkingDir;
si.UserName = txtUserName.Text;
char[] psw = txtPassword.Text.ToCharArray();
SecureString ss = new SecureString();
for (int x = 0; x < psw.Length; x++)
{
    ss.AppendChar(psw[x]);
}
si.Password = ss;
si.Domain = "ABC";
si.RedirectStandardOutput = true;
si.UseShellExecute = false;
si.WorkingDirectory = txtWorkingDir.Text;
p.StartInfo = si;
p.Start();

It isn't that the user/psw isn't matching, because when I provide a bad psw, for example, it catches it. So, this "invalid handle" thing is happening after the cred is passed. Any ideas on what I might be omitting or screwing up?

Veedis answered 9/3, 2009 at 21:58 Comment(0)
S
22

You have to redirect your Input, Error, and Output.

for example:

ProcessStartInfo info = new ProcessStartInfo("cmd.exe");
 info.UseShellExecute = false;
 info.RedirectStandardInput = true;
 info.RedirectStandardError = true;
 info.RedirectStandardOutput = true;
 info.UserName = dialog.User;

 using (Process install = Process.Start(info)) {
       string output = install.StandardOutput.ReadToEnd();
       install.WaitForExit();
       // Do something with you output data       
    Console.WriteLine(output);
 }

Also microsoft has said the error should read, "Unable to redirect input." (used to have a link, but that no longer worked)

Septicidal answered 9/3, 2009 at 22:3 Comment(5)
Wow, yes. I was already setting RedirectStandardOutput to true but not the other two redirects. I set the other two to true and that fixed it! Thanks, @Chris Lively!!Veedis
Cheers for this - I've had fun with this one.Ameeameer
3 years down the link and your post still helps. Pushing a +1. Thanks!Pauwles
Big thanks, man!!! Your answer helped me in 2014. I was running in circles and having no idea what this "invalid handle" actually means. Actually I was trying to print something in the process and it put me on a wrong track - went through a lot of posts where this message appeared because there were problems with printer drivers etc. It's very confusing message and it looks it may appear in dozens of different situations meaning completely different things.Sensuous
you saved my time in 2017!!Fainthearted

© 2022 - 2024 — McMap. All rights reserved.