我从微软支持网站获得此代码 它允许您从应用程序运行外部进程 它在执行程序后给出输出,但我想在屏幕上发生输出 我该怎么做?
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;
}
}
}
答案 0 :(得分:1)
ReadToEnd
显然无效 - 在流关闭之前无法返回(或者它不会读到最后)。相反,使用ReadLine
编写循环。
string line;
while ((line = outputStream.ReadLine()) != null) {
Console.WriteLine("Have line: " + line);
}
另外,将RedirectStandardOutput保留为false
(默认值)将不允许捕获输出,但将 在此上下文中立即显示输出