2009-08-28 93 views
3

如何設置兩個外部可執行文件以從第一個stdout從第二個stdout路由到stdin的c#應用程序運行?將一個進程對象的stdout重定向到另一個進程對象

我知道如何通過使用Process對象來運行外部程序,但我沒有看到像「myprogram1-some -options | myprogram2-some -options」之類的方法。我還需要捕捉第二個程序的標準輸出(在本例中爲myprogram2)。

在PHP中我只是這樣做:

$descriptorspec = array(
      1 => array("pipe", "w"), // stdout 
     ); 

$this->command_process_resource = proc_open("myprogram1 -some -options | myprogram2 -some -options", $descriptorspec, $pipes); 

而且$管[1]將在鏈中的最後一個程序的標準輸出。有沒有辦法在C#中完成這一點?

+0

如果您正在執行大量此類代碼,則可能需要查看Windows PowerShell。 – TrueWill 2009-08-28 23:10:42

+0

我實際上在Linux中這樣做,但感謝提示! – Matthew 2009-08-31 12:30:45

+0

我從來不知道管道操作員,我只是爲了告訴你,謝謝你。這是一個了不起的運營商。 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true – jocull 2010-03-04 00:50:29

回答

10

下面是將一個過程的標準輸出連接到另一個過程的標準輸入的基本示例。

Process out = new Process("program1.exe", "-some -options"); 
Process in = new Process("program2.exe", "-some -options"); 

out.UseShellExecute = false; 

out.RedirectStandardOutput = true; 
in.RedirectStandardInput = true; 

using(StreamReader sr = new StreamReader(out.StandardOutput)) 
using(StreamWriter sw = new StreamWriter(in.StandardInput)) 
{ 
    string line; 
    while((line = sr.ReadLine()) != null) 
    { 
    sw.WriteLine(line); 
    } 
} 
+0

這正是我需要看到的。非常感謝! – Matthew 2009-08-31 12:24:51

0

您可以使用System.Diagnostics.Process類創建2個外部進程,並通過StandardInput和StandardOutput屬性將輸入和輸出連接在一起。

+0

我不認爲這實際上起作用。您提到的屬性是隻讀的。因此,如果通過「一起進出」,你的意思是像'proc2.StandardInput = proc1.StandardOutput;'這樣的分配,那麼我相信這是一個無法回答的問題。也許你可以澄清。 – 2013-07-08 21:48:06

0

使用System.Diagnostics.Process啓動每個進程,並在第二個進程中將RedirectStandardOutput設置爲true,並在第一個RedirectStandardInput爲true。最後將第一個的StandardInput設置爲StandardOutput的第二個。您需要使用ProcessStartInfo來啓動每個進程。

這是一個example of one的重定向。

+0

與@ Mischa的帖子相同的評論。 StandardInput和StandardOutput屬性不僅是隻讀的,而且它們是不同的類型(分別爲StreamWriter和StreamReader)。所以你不能把它們分配給對方。 – 2013-07-08 21:50:33

相關問題