3

I am running a command line utility using Process.Start. For debugging purposes I would like to have its output stream to Visual Studio's Debug Output panel (Debug.Write). I'd like to do this in real time rather than waiting for the process to complete and then writting it all at once.

I know this is possible in theory but I'm not experienced enough with the Stream object to know how to do this.

George Mauer
  • 110,852
  • 124
  • 360
  • 595

2 Answers2

5

This may not be exactly what you want, but it puts you on the right track, I think.

p.StartInfo.UseShellExecute = false; 
p.StartInfo.RedirectStandardOutput = true;
p.OutputDataReceived += p_OutputDataReceived;
p.Start();
p.BeginOutputReadLine();

Then, your event handler for receiving data.

void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
    Debug.Write(e.Data);
}
Gray
  • 6,916
  • 2
  • 28
  • 49
  • 1
    Thank you sir - that's it exactly. Just one note, you can't use this technique AND `p.StandardOuptut.ReadToEnd()` You have to create a `StringBuilder` and build it up yourself in the event handler. Easy enough, just something to be aware of. – George Mauer Jun 28 '13 at 18:18
  • How can we pipe a custom data, such as a % of data processed to p_OutputDataReceived from calling scope – BGT Jan 28 '22 at 10:56
2

CliWrap makes working with processes trivial. Here's how your particular scenario would look:

// Pipe the output directly to Debug.WriteLine
var cmd = Cli.Wrap("app.exe") | Debug.WriteLine;

await cmd.ExecuteAsync();
Tyrrrz
  • 2,195
  • 1
  • 19
  • 22
  • oh jeezus, they overload the pipe operator? In c#? Well...it's a fun idea, I wouldn't say a good one, but. a fun one – George Mauer Apr 15 '20 at 21:15
  • Well it's a pipe operator for a reason ;) Wait till you see the pipe operator combined with value tuple. – Tyrrrz Apr 16 '20 at 13:57