2014-08-31 77 views
-1

我从微软支持网站 得到这段代码,它允许你从你的应用程序运行一个外部进程 它给程序执行后输出,但我想流输出,因为它发生在屏幕上 我该怎么做?如何对流程的输出进行流式处理?

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; 
    } 
} 
} 
+2

你想实现什么?这不是提问的一种方式。 – 2014-08-31 08:38:31

+1

流输出,而不是等待它完成并显示输出@KaushikKishore – user3155632 2014-08-31 08:41:02

回答

1

ReadToEnd显然是行不通的 - 它无法返回流被关闭之前(或者它不会读到尾)。相反,使用ReadLine编写一个循环。

string line; 
while ((line = outputStream.ReadLine()) != null) { 
    Console.WriteLine("Have line: " + line); 
} 

此外,保持RedirectStandardOutput作为false(缺省值)将不允许输出被捕获,但它会在此上下文中在屏幕上立即显示输出。