Search code examples
c#visual-studiovisual-studio-2008stdoutoutput-window

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


Solution

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