How to write to the stdin of another app?
Asked Answered
P

3

7

I have a module that reads the StandardError of a process. Everything works fine, but I want to do something different. I don't know how to redirect stdin like the native way:

app1.exe -someargs | app2.exe -someargs

Where app2 reads all the stdout of app1 in its stdin.

Preempt answered 10/4, 2010 at 11:16 Comment(3)
This answer should give you a good idea C# Console receive input with pipeAvellaneda
But the second application is not written by me. I need to send bytes to subprocess, not receive them.Preempt
@blez, it should be pretty obvious. Writing is the opposite of reading. Where the linked answer tells you to read from the Console, you Write to the Console.Feverish
G
3

Have a look at the MSDN reference documentation for the following (both to be found in the System.Diagnostics namespace):

For your particular example, here's how you set things up:

  1. app1 starts app2 as a child process using the Process class (see links above).

  2. app1 writes to app2's standard input by writing to the .StandardInput stream of the Process object associated with app2.

  3. app2 just reads lines from its standard input (e.g. via Console.ReadLine()).

Grantor answered 10/4, 2010 at 11:38 Comment(0)
E
9

Once you have the Process object representing the process you want to communicate with (either because you got it from the OS using the static method Process.GetProcesses, or because you created it yourself), you can attach a StreamWriter to the Process.StandardInput property and use that to write to the stdin of the process. Don't forget to set ProcessStartInfo.RedirectStandardInput on your newly created process to true.

On a related note, you can use a StreamReader on the Process.StandardOutput to read the output (like reading from StandardError).

Expellee answered 10/4, 2010 at 11:36 Comment(0)
G
3

Have a look at the MSDN reference documentation for the following (both to be found in the System.Diagnostics namespace):

For your particular example, here's how you set things up:

  1. app1 starts app2 as a child process using the Process class (see links above).

  2. app1 writes to app2's standard input by writing to the .StandardInput stream of the Process object associated with app2.

  3. app2 just reads lines from its standard input (e.g. via Console.ReadLine()).

Grantor answered 10/4, 2010 at 11:38 Comment(0)
P
1

I had to use BinaryWriter, this article explains all: BinaryWriter and StdIn

Preempt answered 10/4, 2010 at 11:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.