Reputation: 279
How do I check whether the process executed successfully in C# code? Below is the code I used to check. Is it enough to check p.ExitCode = 0
for successful execution? If it is so, then how do I get the description of the error if I get any error, (i.e) ExitCode <> 0
?
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/c " + command);
psi.RedirectStandardOutput = false;
psi.RedirectStandardError = false;
psi.UseShellExecute = true;
psi.CreateNoWindow = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
Process p = new Process();
p.StartInfo = psi;
p.Start();
p.WaitForExit();
MessageBox.Show("Error Code:" + p.ExitCode);
Upvotes: 3
Views: 8890
Reputation: 131
psi.StandardError.ReadtoEnd()
should get you the error code as a string.
One catch is psi.UseShellExecute = false
. Hope this helps.
Upvotes: 1
Reputation: 612954
The meaning of the process exit code is defined by the process. A process may fail, and still return a zero error code. A process may succeed and return a non-zero error code. Although clearly those two possibilities go against convention.
In order to interpret the error code therefore, you need to consult the documentation of the process that you are executing. Often that documentation is non-existent and sometimes the most expedient approach is to read the standard output and/or standard error streams and parse that text to find an error message.
For what it is worth, your code seems needlessly complex, and you should not be setting UseShellExecute
to true
here. Code like this would seem more clean:
ProcessStartInfo psi = new ProcessStartInfo("cmd.exe", "/c " + command);
psi.UseShellExecute = false;
psi.CreateNoWindow = true;
Process process = Process.Start(psi);
process.WaitForExit();
Upvotes: 6