如何获取 System.Diagnostics.Process 的输出?

2024-02-18

我这样运行 ffmpeg:

System.Diagnostics.Process p = new System.Diagnostics.Process();
p.StartInfo = new System.Diagnostics.ProcessStartInfo(ffmpegPath, myParams);
p.Start();
p.WaitForExit();

...但问题是带有 ffmpeg 的控制台弹出并立即消失,所以我无法得到任何反馈。我什至不知道该过程是否正确运行。

那么我怎样才能:

  • 告诉控制台保持打开状态

  • 在 C# 中检索控制台的内容 显示的


您需要做的是捕获标准输出流:

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
// instead of p.WaitForExit(), do
string q = "";
while ( ! p.HasExited ) {
    q += p.StandardOutput.ReadToEnd();
}

您可能还需要执行类似的操作StandardError。然后你可以做你想做的事q.

正如我在中发现的那样,这有点挑剔我的问题之一 https://stackoverflow.com/questions/1060799/c-shell-io-redirection

正如乔恩·斯基特(Jon Skeet)指出的那样,使用这样的字符串连接在性能方面并不明智;你应该使用StringBuilder http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx:

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
// instead of p.WaitForExit(), do
StringBuilder q = new StringBuilder();
while ( ! p.HasExited ) {
    q.Append(p.StandardOutput.ReadToEnd());
}
string r = q.ToString();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何获取 System.Diagnostics.Process 的输出? 的相关文章

随机推荐