views:

301

answers:

3

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.)

A: 

Have you considered using duct tape and bailing wire?

GenEric35
This doesn't even *remotely* answer my question. And from the linked MSDN page: "An instance of this class is automatically added to the Debug.Listeners and Trace.Listeners collections. Explicitly adding a second DefaultTraceListener causes duplicate messages in the debugger output window and duplicate message boxes for asserts.", making your answer worse than totally useless.
Andrew Russell
Revenge downvote, eh? Stay classy, GenEric35.
Andrew Russell
+1  A: 

What's going on here is that Visual Studio is displaying the debug output from the program in the Output Window. That is: if you use Trace.WriteLine, it'll appear in the Output Window, because of the default trace listener.

Somehow, your Windows Form application (when it uses Console.WriteLine; I'm assuming you're using Console.WriteLine) is also writing debug output, and Visual Studio is picking this up.

It won't do the same for child processes, unless you explicitly capture the output and redirect it along with your output.

Roger Lipscombe
That's basically what I'm trying to ask - how do you do the last bit? (And, I realised I was missing this from my question: how to do it "as it happens"?)
Andrew Russell
+2  A: 
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.OutputDataReceived  += (sender, args) => Console.WriteLine(args.Data);
process.BeginOutputReadLine();

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

Mark H
This answer is mostly right. It's missing some stuff. In particular: `Start` call before `Begin...ReadLine` and `WaitForExit` afterwards. Also setting `RedirectStandardInput` to true fixed a problem caused by one of the programs (specifically plink) in the batch file wanting a valid stdin, even though it didn't use it.
Andrew Russell