2014-08-31 92 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(缺省值)將不允許輸出被捕獲,但它會在此上下文中在屏幕上立即顯示輸出。

相關問題