13

I am trying to run a process in c# using the Process class.

Process p1  = new process();
p1.startinfo.filename =  "xyz.exe";
p1.startinfo.arguments = //i am building it based on user's input.
p1.start();

So based on user input i am building the argument value. Now i have a case where i have to pipe the output of p1 to another process say grep. so i basically tried this

p1.startinfo.arguments = "-info |grep 1234" ;

what i intended is something like xyz.exe -info|grep 1234

but this doesn't seem to work in .net .. I can actually create another process variable and run "grep" as a separate process.. But i was wondering if there is any way to do as iam trying out above..

FatDaemon
  • 766
  • 2
  • 8
  • 13
  • I found this blog article which covers exactly this question: [Using piped output redirection on the Process/ProcessStartInfo classes...](http://weblogs.asp.net/justin_rogers/archive/2004/02/27/81370.aspx) – Sam Harwell Aug 17 '09 at 22:10
  • If you don't want to use CMD, check out the [MedallionShell](https://github.com/madelson/MedallionShell) library. It makes process stream redirection (and other aspects of process management) much simpler. – ChaseMedallion Aug 24 '14 at 18:12

1 Answers1

22

The much easier way would be to do just use cmd as your process.

Process test = new Process();
test.StartInfo.FileName = "cmd";
test.StartInfo.Arguments = @"/C ""echo testing | grep test""";
test.Start();

You can capture the output or whatever else you want like any normal process then. This was just a quick test I built, but it works outputting testing to the console so I would expect this would work for anything else you plan on doing with the piping. If you want the command to stay open then use /K instead of /C and the window will not close once the process finishes.

Mark
  • 867
  • 8
  • 12
  • 1
    I need to do the same thing without cmd on linux. How can I connect the StreamReader of the source process with the StreamWriter of the target process? – feedc0de May 25 '15 at 12:13
  • 1
    and how to do that in Linux? :) – knocte Jun 07 '16 at 09:31
  • How to do exactly the same with Linux :) – Saw Jul 17 '17 at 04:02
  • Basically for Linux you'd replace "cmd" with "bash -c". Resulting in something like info.FileName = "/bin/bash"; info.Arguments = "-c \"top -bn1 | grep 'Cpu(s)' | sed 's/.*, *\\([0-9.]*\\)%* id.*/\\1/' \""; this example works getting me the free CPU %. – Nick Kovalsky Feb 04 '22 at 20:01