2009-08-28 2 views
3

C#アプリケーションから実行する外部実行ファイルを2つ設定するにはどうしたらよいですか?あるプロセスオブジェクトのstdoutを別のプロセスオブジェクトのstdinにリダイレクト

私はProcessオブジェクトを使って外部プログラムを実行する方法を知っていますが、 "myprogram1 -some -options | myprogram2 -some -options"のような方法はありません。私はまた、2番目のプログラム(この例では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

+0

私は実際にLinuxでこれをやっていますが、ヒントをいただきありがとうございます! – Matthew

+0

私は配管オペレータについて知らなかったので、あなたに感謝するためにログインしました。それは素晴らしいオペレータです。 http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true – jocull

答えて

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

0

System.Diagnostics.Processクラスを使用して、2つの外部プロセスを作成し、StandardInputプロパティとStandardOutputプロパティを使用してインとアウトを結合することができます。

+0

これは実際には動作しないと思います。あなたが言及するプロパティは読み取り専用です。ですから、 '一緒に出入りするようにする'ならば、あなたは 'proc2.StandardInput = proc1.StandardOutput;'のような割り当てをしていれば、これは無回答と信じています。おそらくあなたは明らかにすることができます。 –

0

System.Diagnostics.Processを使用して各プロセスを開始し、2番目のプロセスではRedirectStandardOutputをtrueに設定し、最初のRedirectStandardInputをtrueに設定します。最後に、最初のStandardInputを2番目のStandardInputに設定します。 ProcessStartInfoを使用して各プロセスを開始する必要があります。

ここには、リダイレクトのexample of oneがあります。

+0

@ Mischaの投稿と同じコメントです。 StandardInputプロパティとStandardOutputプロパティは読み取り専用ですが、それぞれ異なるタイプ(それぞれStreamWriterとStreamReader)です。だからあなたはそれらを(互いに)割り当てることはできません。 –

関連する問題