tags:

views:

1101

answers:

2

Is it possible to run a console application and get its outputted contents back as a string in C#?

I want to be able to use parameters when running the console app:

c:\files\app.exe -a 1 -b 2 -c 3
+3  A: 

You want to use the Process class's Start method and redirect the output to a StreamReader.

Here's an example.

rein
thanks, exactly what i was looking for. is there anyway to stop the main form from not responding until the console app returns?
Put it in a BackgroundWorker. ( http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx )
lc
+1  A: 

This isn't the clearest thing I've read today, but I can only assume you're spawning a process (with Process.Start()?) and want to get it's output back into your program.

If so, Process.StandardOutput is probably what you're looking for. For example:

System.Diagnostics.ProcessStartInfo startInfo = 
    new System.Diagnostics.ProcessStartInfo(@"c:\files\app.exe",@"-a 1 -b 2 -c 3"); 
startInfo.UseShellExecute = false; 
startInfo.RedirectStandardOutput = true; 
Process p = Process.Start(startInfo);
string output = p.StandardOutput.ReadToEnd();
p.WaitForExit();
lc
i kept getting errors from this one saying that new process does not have a constructor that accepts only 1 param
Sorry about that. Fixed it.
lc
My application can not show its window until started process is running. When i killed it then my application showed its window with captured output. I'm using this code exactly as it is with one more property - CreateNoWindow. How to show my application "normally"?
Laserson
@Laserson You mean you're having trouble getting your application to show its console window until the process `p` is running? As in it looks like your CreateNoWindow is applying itself to the *current process* as well as the one started? Or am I totally misunderstanding?
lc
@lc No, i have a normal WinForms application. It starts a console encoder (mencoder). I need to get an output of this encoder and for example show it on my form. But my form doesn't appear until encoder process is running. Is it possible to get console output in the "real time"?
Laserson
@Laserson The only thing I can think of off-hand is it has something to do with where the above code is living. If it's being called from the `Form.Load` event, for example, the process will be started before the form is shown (and act like the behavior you're describing).However, the more I think about it, the more it looks like you're running this code on the same thread as the UI and it's being blocked at `p.WaitForExit()`. Try putting the above in a `BackgroundWorker` which reports progress, then use the progress reporting to send messages back to the UI thread.
lc