Redirecting stdout of one process object to stdin of another

后端 未结 4 747
谎友^
谎友^ 2020-12-15 01:42

How can I set up two external executables to run from a c# application where stdout from the first is routed to stdin from the second?

I know how to run external pro

相关标签:
4条回答
  • 2020-12-15 02:25

    Here's a basic example of wiring the standard output of one process to the standard input of another.

    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 讨论(0)
  • 2020-12-15 02:28

    You can use a library I made called CliWrap. It supports very expressive syntax for piping shell commands. It works with binary streams directly so it's more efficient than decoding strings or buffering data in-memory.

    var cmd = Cli.Wrap("myprogram1").WithArguments("-some -options") |
              Cli.Wrap("myprogram2").WithArguments("-some -options");
    
    await cmd.ExecuteAsync();
    

    More info on piping here: https://github.com/Tyrrrz/CliWrap#piping

    0 讨论(0)
  • 2020-12-15 02:33

    Use System.Diagnostics.Process to start each process, and in the second process set the RedirectStandardOutput to true, and the in the first RedirectStandardInput true. Finally set the StandardInput of the first to the StandardOutput of the second . You'll need to use a ProcessStartInfo to start each process.

    Here is an example of one of the redirections.

    0 讨论(0)
  • 2020-12-15 02:37

    You could use the System.Diagnostics.Process class to create the 2 external processes and stick the in and outs together via the StandardInput and StandardOutput properties.

    0 讨论(0)
提交回复
热议问题