2013-10-24 20 views
0

我試圖從c#運行批處理文件,使用下面的代碼,我想在WPF文本框中顯示結果。你能指導我如何做到這一點?在文本框中顯示批量輸出

using System; 

namespace Learn 
{ 
    class cmdShell 
    { 
     [STAThread] // Lets main know that multiple threads are involved. 
     static void Main(string[] args) 
     { 
      System.Diagnostics.Process proc; // Declare New Process 
      proc = System.Diagnostics.Process.Start("C:\\listfiles.bat"); // run test.bat from command line. 
      proc.WaitForExit(); // Waits for the process to end. 
     } 
    } 
} 

此批處理文件是列出文件夾中的文件。一旦批次執行結果應顯示在文本框中。如果批處理文件有多個命令,則每個命令的結果應顯示在文本框中。

+0

結果瞬間輸出的問題,從不同的文件因此不同的水垢過程中,您可以使用管道(或WCF)訪問您的應用程序,您將無法剔除這些結果 – Izikon

回答

0

我已經解決了與工藝掛,並得到如下

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Process proc = new Process(); 
      proc.StartInfo.FileName = "test.bat"; 
      proc.StartInfo.UseShellExecute = false; 
      proc.StartInfo.RedirectStandardOutput = true; 
      proc.OutputDataReceived += proc_OutputDataReceived; 
      proc.Start(); 
      proc.BeginOutputReadLine(); 
     } 
    } 


     void proc_OutputDataReceived(object sender, DataReceivedEventArgs e) 
     { 
      this.Dispatcher.Invoke((Action)(() => 
         { 
          txtprogress.Text = txtprogress.Text + "\n" + e.Data; 
          txtprogress.ScrollToEnd(); 
         })); 
     } 
} 
2

您需要的標準輸出流重定向:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Diagnostics; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Process proc = new Process(); 
      proc.StartInfo.FileName = "test.bat"; 
      proc.StartInfo.UseShellExecute = false; 
      proc.StartInfo.RedirectStandardOutput = true; 
      proc.Start(); 
      string output = proc.StandardOutput.ReadToEnd(); 
      Console.WriteLine(output); // or do something else with the output 
      proc.WaitForExit(); 
      Console.ReadKey(); 
     } 
    } 
} 
+0

是的,這工作正常。但執行完成後會顯示輸出,有什麼需要添加的? – Ponmalar

+0

Process'類的'StandardOutput'屬性是[StreamReader](http://msdn.microsoft.com/en-us/library/vstudio/system.io.streamreader)實例。您不需要等待執行結束。例如:如果在循環中使用'proc.StandardOutput.ReadLine()',則可以等待下一行被寫入並立即將其推送到文本框。有關更多信息,請參閱文檔。 – Shinja