0

How can I capture or redirect an error that occurs for a Process?

I want to be able to get the error msg info.

The code below doesn't do it.

try
{
    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.FileName = process_to_run;
    myProcess.StartInfo.Arguments = p_arg + " > "+process_to_run+".txt 2>&1";
    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.Start();
    myProcess.WaitForExit();

}
catch (Exception ep)
{
    richTextBox1.AppendText("\n" + ep.Message);
    time_date = get_time();
    log_file.Write(time_date);
    log_file.WriteLine(process_to_run + "...Failed. ERROR: " + ep.Message);
}
Tuna
  • 55
  • 1
  • 7
John Ryann
  • 2,283
  • 11
  • 43
  • 60
  • 1
    Possible duplicate of: http://stackoverflow.com/questions/4587415/how-to-capture-shell-command-output-in-c – qJake Jun 28 '12 at 20:39

1 Answers1

2

You can redirect the standard error, then parse that to determine if there was an error.

// Start the child process.
 Process p = new Process();
 // Redirect the error stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardError = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected error stream.
 // p.WaitForExit();
 // Read the error stream first and then wait.
 string error = p.StandardError.ReadToEnd();
 p.WaitForExit();
John Koerner
  • 37,428
  • 8
  • 84
  • 134