将一个进程对象的stdout重定向到另一个进程对象的stdin

如何设置两个外部可执行文件从ac#应用程序运行,其中第一个stdout从第二个路由到stdin?

我知道如何使用Process对象运行外部程序,但我没有看到像“myprogram1 -some -options | myprogram2 -some -options”这样的方法。 我还需要捕获第二个程序的stdout(示例中的myprogram2)。

在PHP中我会这样做:

$descriptorspec = array( 1 => array("pipe", "w"), // stdout ); $this->command_process_resource = proc_open("myprogram1 -some -options | myprogram2 -some -options", $descriptorspec, $pipes); 

$ pipes [1]将成为链中最后一个程序的标准输出。 有没有办法在c#中实现这一目标?

这是将一个过程的标准输出连接到另一个过程的标准输入的基本示例。

 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); } } 

您可以使用System.Diagnostics.Process类创建2个外部进程,并通过StandardInput和StandardOutput属性将输入和输出粘在一起。

使用System.Diagnostics.Process启动每个进程,在第二个进程中将RedirectStandardOutput设置为true,并将第一个RedirectStandardInput设置为true。 最后将第一个的StandardInput设置为第二个的StandardOutput。 您需要使用ProcessStartInfo来启动每个进程。

以下是其中一个重定向的示例 。