Stephan Pillhofer
Stephan Pillhofer

Reputation: 147

C# redirecting data to an already running console exe

What I want todo:

I want to start a built console application (AppB) from within another console application (AppA). AppA starts AppB without any arguments. All AppB does is to go into its Main() Method and call Console.ReadLine().

Now I want that AppA sends a string of data over to AppB's Console.ReadLine(). Is this even possibel? (I know I can send streams to a new Console.exe but that's not what I need.)

Upvotes: 0

Views: 57

Answers (1)

hcham1
hcham1

Reputation: 1847

You need to use RedirectStandardInput:

     Process myProcess = new Process();

     myProcess.StartInfo.FileName = "someconsoleapp.exe";
     myProcess.StartInfo.UseShellExecute = false;
     myProcess.StartInfo.RedirectStandardInput = true;
     myProcess.StartInfo.RedirectStandardOutput = true;
     myProcess.StartInfo.ErrorDialog = false;

     myProcess.Start();

     StreamWriter stdInputWriter  = myProcess.StandardInput;
     StreamReader stdOutputReader  = myProcess.StandardOutput;

     stdInputWriter.WriteLine(password);

     var op = stdOutputReader.ReadLine();

     // close this - sending EOF to the console application - hopefully well written
     // to handle this properly.
     stdInputWriter.Close();


     // Wait for the process to finish.
     myProcess.WaitForExit();
     myProcess.Close();

Upvotes: 1

Related Questions