3 回答

TA貢獻(xiàn)1801條經(jīng)驗(yàn) 獲得超16個贊
這是我驗(yàn)證過的代碼。我使用它來生成MSBuild并監(jiān)聽它的輸出:
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine("received output: {0}", args.Data);
process.Start();
process.BeginOutputReadLine();

TA貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超3個贊
我需要捕獲stdout和stderr,如果進(jìn)程沒有在預(yù)期的情況下退出,則需要超時。我想出了這個:
Process process = new Process();
StringBuilder outputStringBuilder = new StringBuilder();
try
{
process.StartInfo.FileName = exeFileName;
process.StartInfo.WorkingDirectory = args.ExeDirectory;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.EnableRaisingEvents = false;
process.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.ErrorDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
var processExited = process.WaitForExit(PROCESS_TIMEOUT);
if (processExited == false) // we timed out...
{
process.Kill();
throw new Exception("ERROR: Process took too long to finish");
}
else if (process.ExitCode != 0)
{
var output = outputStringBuilder.ToString();
var prefixMessage = "";
throw new Exception("Process exited with non-zero exit code of: " + process.ExitCode + Environment.NewLine +
"Output from process: " + outputStringBuilder.ToString());
}
}
finally
{
process.Close();
}
我正在將stdout和stderr連接到相同的字符串中,但是如果需要的話,您可以將它分開。它使用事件,所以它應(yīng)該處理它們的到來(我相信)。我已經(jīng)成功地運(yùn)行了這個程序,并將很快進(jìn)行卷測試。
- 3 回答
- 0 關(guān)注
- 591 瀏覽
添加回答
舉報