C# 如何在流程发生时将其输出流化?

C# 如何在流程发生时将其输出流化?,c#,.net,C#,.net,我从microsoft支持站点获得了此代码 它允许您从应用程序运行外部进程 它在程序执行后给出输出,但我想在屏幕上显示流式输出 我该怎么做 using System; using System.Diagnostics; using System.IO; namespace Way_Back_Downloader { internal class RunWget { internal static string Run(string exeName, string argsLine,

我从microsoft支持站点获得了此代码 它允许您从应用程序运行外部进程 它在程序执行后给出输出,但我想在屏幕上显示流式输出 我该怎么做

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
显然不起作用-它不能在流关闭之前返回(否则它不会一直读到最后)。相反,使用编写循环


另外,保持为
false
(默认值)将不允许捕获输出,但它会在该上下文中立即在屏幕上显示输出。

您想要实现什么?这不是一种询问question.stream输出的方式,而是等待它完成并显示output@kaushikishore
string line;
while ((line = outputStream.ReadLine()) != null) {
   Console.WriteLine("Have line: " + line);
}