捕获外部进程的错误

时间:2012-06-28 20:35:40

标签: c# process error-handling

如何捕获或重定向Process发生的错误?

我希望能够获得错误消息信息。

以下代码不会这样做。

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);
}

1 个答案:

答案 0 :(得分:2)

你可以redirect the standard 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();