如何在流程输出发生时对其进行流式传输
本文关键字:传输 程输 出发 | 更新日期: 2023-09-27 18:20:16
我从微软支持网站获得了这段代码它允许您从应用程序运行外部进程它在程序执行后提供输出,但我希望在屏幕上进行流式输出我该怎么做?
using System;
using System.Diagnostics;
using System.IO;
namespace Way_Back_Downloader
{
internal class RunWget
{
internal static string Run(string exeName, string argsLine, int timeoutSeconds)
{
StreamReader outputStream = StreamReader.Null;
string output = "";
bool success = false;
try
{
Process newProcess = new Process();
newProcess.StartInfo.FileName = exeName;
newProcess.StartInfo.Arguments = argsLine;
newProcess.StartInfo.UseShellExecute = false;
newProcess.StartInfo.CreateNoWindow = true;
newProcess.StartInfo.RedirectStandardOutput = true;
newProcess.Start();
if (0 == timeoutSeconds)
{
outputStream = newProcess.StandardOutput;
output = outputStream.ReadToEnd();
newProcess.WaitForExit();
}
else
{
success = newProcess.WaitForExit(timeoutSeconds * 1000);
if (success)
{
outputStream = newProcess.StandardOutput;
output = outputStream.ReadToEnd();
}
else
{
output = "Timed out at " + timeoutSeconds + " seconds waiting for " + exeName + " to exit.";
}
}
}
catch (Exception exception)
{
throw (new Exception("An error occurred running " + exeName + ".", exception));
}
finally
{
outputStream.Close();
}
return "'t" + output;
}
}
}
ReadToEnd
显然不起作用——它在流关闭之前不能返回(否则它不会读到最后)。相反,使用ReadLine
编写一个循环。
string line;
while ((line = outputStream.ReadLine()) != null) {
Console.WriteLine("Have line: " + line);
}
此外,将RedirectStandardOutput保持为false
(默认值)将不允许捕获输出,但在这种情况下,它将立即在屏幕上显示输出。