Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect the output (stdout, stderr) of a child process to the Output window in Visual Studio

At the moment I am starting a batch file from my C# program with:

System.Diagnostics.Process.Start(@"DoSomeStuff.bat");

What I would like to be able to do is redirect the output (stdout and stderr) of that child process to the Output window in Visual Studio (specifically Visual C# Express 2008).

Is there a way to do that?

(Additionally: such that it's not all buffered up and then spat out to the Output window when the child process finishes.)


(BTW: At the moment I can get stdout (but not stderr) of the parent process to appear in the Output window, by making my program a "Windows Application" instead of a "Console Application". This breaks if the program is run outside Visual Studio, but this is ok in my particular case.)

like image 941
Andrew Russell Avatar asked Sep 04 '10 12:09

Andrew Russell


People also ask

What is redirecting stderr to stdout?

The regular output is sent to Standard Out (STDOUT) and the error messages are sent to Standard Error (STDERR). When you redirect console output using the > symbol, you are only redirecting STDOUT. In order to redirect STDERR, you have to specify 2> for the redirection symbol.

What is the output in the child process?

The read end of one pipe serves as standard input for the child process, and the write end of the other pipe is the standard output for the child process.

What is stdout C#?

Stdout means "Standard Output". This typically refers to the console.


1 Answers

process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived += (sender, args) => Console.WriteLine(args.Data);
process.Start();
process.BeginOutputReadLine();

process.WaitForExit();

Same idea for Error, just replace Output in those method/property names.

like image 188
Mark H Avatar answered Sep 21 '22 11:09

Mark H