Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect output of one exe to another exe : C#

Tags:

redirect

c#

I have created two simple .exe files. One of them takes a filename parameter at runtime and reads the contents of the file to the console. The other waits on its console's input and then reads it; for now it just has to print out to the console, but eventually I'll have to redirect the read in text to a new txt file. My question is, how can I redirect the output of the first exe to the 2nd exe's console where it can be read in?

Thanks in advance for any help you can provide! :)

-Chris

like image 619
Chris V. Avatar asked Oct 16 '11 23:10

Chris V.


2 Answers

You could probably do something with the command line using the pipe redirect operator:

ConsoleApp1.exe | ConsoleApp2.exe

The pipe operator redirects the console output from the first app to the standard input of the second app. You can find more info here (the link is for XP but the rules apply to Windows Vista and Windows 7 as well).

like image 184
Jeff Siver Avatar answered Nov 02 '22 16:11

Jeff Siver


From MSDN

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

you could get a line by line read instead by:

///...
string output;
while( ( output = p.StandardOutput.ReadLine() ) != null )
{
    Console.WriteLine(output);
}
p.WaitForExit();
like image 30
spender Avatar answered Nov 02 '22 15:11

spender