我目前有一部分代码可以创建一个新进程并从 shell 执行它。
Process p = new Process();
...
p.Start();
p.WaitForExit();
这使得窗口在进程运行时保持打开状态,这很棒。不过,我也想把窗户打开after完成查看潜在消息。有没有办法做到这一点?
更容易捕获输出 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.beginoutputreadline(v=vs.110).aspx来自两个标准输出 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput(v=vs.110).aspx和标准误差 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standarderror(v=vs.110).aspx,将每个输出存储在 StringBuilder 中,并在该过程完成时使用该结果。
var sb = new StringBuilder();
Process p = new Process();
// redirect the output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
// hookup the eventhandlers to capture the data that is received
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);
// direct start
p.StartInfo.UseShellExecute=false;
p.Start();
// start our event pumps
p.BeginOutputReadLine();
p.BeginErrorReadLine();
// until we are done
p.WaitForExit();
// do whatever you need with the content of sb.ToString();
您可以在中添加额外的格式sb.AppendLine
区分标准输出和错误输出的语句,如下所示:sb.AppendLine("ERR: {0}", args.Data);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)