Process.StandardOutput

  • Thread starter Thread starter Steve
  • Start date Start date
S

Steve

I am using Diagnostics.Process to, well.. execute a process. I would like
to display the output of the process to my UI as it is created. For
example, ping www.yahoo.com will slowly output each result. I want to
display that output as it happens in my UI.

I don't see a clean way to do this. After my Start() call, I made a call to
StandardOutput.ReadToEnd() but it appears to hang until the process finishes
(makes sense) But what do you suggest I do to get the output as it's
generated?

One thing I realize is that I will need to launch the process in a separate
thread to free the UI to be able to display the output.

Hope someone has done this and can help. Thanks in advance,
Steve
 
try something like this:

Process p = new Process();

p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.UseShellExecute = false;
p.StartInfo.FileName = @"C:\WINDOWS\system32\ping.exe";
p.StartInfo.Arguments = "192.168.1.1";
p.Start();

while (!p.StandardOutput.EndOfStream) {
Console.WriteLine(p.StandardOutput.ReadLine());
}
 
I launch separate threads to read from the StandardOut and StandardError
streams. You can launch the process from the main thread, launch the monitor
threads, and then the main thread can return. It's important to read the
data from each stream quickly because the application will block if the
stream fills up. If you use ReadToEnd it will return when the application
exits.

You can use ReadLine to read each line of data as it is written; when the
application has exited it will return null...this is when the monitor thread
can exit. It might also throw an exception - I think this means that an EOF
as read. Again, this means the app has exited. The code sits in a loop
reading lines and periodically (a few times per second) updating the
display.

You might want to run these threads at a reduced priority to give more
processing time to the application.
 
Hi, thanks for the reply!

I just attempted to implement your suggestion, but I don't see that
EndOfStream is a valid property. I get a compiler error when I try to use
it.
I tried using Peek() != 0 just to see what would happen, it didn't go well
;)
 
Hi David,

I will need to read this a couple more times, but it sounds like it might be
what I want. I was hoping it would be simpler, but this sounds like it is
all necessary, so I will try this out.
Thanks for the post!
Steve
 
Back
Top