capture console application output into textbox

I need to launch a console application from my c# application.
While the console application is running(and it outputs text to the console), my c# application should capture the output in realtime, and fill a textbox with it.
I can't upload a console application here, so please use one of your choice.
Thanks
themaniacAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jens FiedererTest Developer/ValidatorCommented:
When you say "output text to the console" are you specifying you want to run the console app to output to an ACTUAL console window rather than redirecting its output to a file?

You can run a console app and redirect its output to a file, then use your c# app to read the file  (there CAN be buffering issues here, though, depending on how often the console app flushes its output).
0
themaniacAuthor Commented:
The output should be redirected to the c# app,  but not displayed to the console(or better, do not display the console app while running). I want to do this without files.
Again:
1. the c# launches the console app
2. the console app DOES NOT display anything, it should run "hidden"
3. the console app should redirect its output to the c# app.

0
Jens FiedererTest Developer/ValidatorCommented:
Sounds like a job for a pipe!
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Jens FiedererTest Developer/ValidatorCommented:
Take a look at the docs for "anonymous pipes"
0
Jens FiedererTest Developer/ValidatorCommented:
Even simpler, you can use the Process.StartInfo  to redirect the standard output.

From MSDN docs:

// Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();
0
Jens FiedererTest Developer/ValidatorCommented:
In your case, of course, you sound like you'd rather to the occasional .ReadLine or even asynchronous stream I/O to send your text to your textbox, not a ReadToEnd.
0
themaniacAuthor Commented:
Great, but how do I know when to do the Readline, if the console application outputs some text from time to time?
0
Jens FiedererTest Developer/ValidatorCommented:
That's what I meant with the asynchronous stream I/O.

You can do a "BeginRead" on the stream and specify a callback function to call when you get some text.
0
themaniacAuthor Commented:
Sounds nice. Could you please give me an example? I never used callbacks so I don't know how to use them for capturing the output, as you say
Thank you
0
Jens FiedererTest Developer/ValidatorCommented:
Sure...let's say we have this as our console app...
Just generates a bunch of lines with random 0-10 second intervals between.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
 
namespace OutputGenerator
{
    class Program
    {
        static void Main(string[] args)
        {
            Random generator = new Random();
            int max = 10 + generator.Next(500);
            for (int i = 0; i < generator.Next(500); i++)
            {
                int wait = generator.Next(10);
                Console.WriteLine(i.ToString() + " out of " + max.ToString() + " items - " + wait.ToString());
                Thread.Sleep(1000 * wait);
            }
        }
    }
}

Open in new window

0
Jens FiedererTest Developer/ValidatorCommented:
In our main app, we use "ProcessRead" as our callback
// Where we start the child process.
             p = new Process();
             // Redirect the output stream of the child process.
             p.StartInfo.UseShellExecute = false;
             p.StartInfo.RedirectStandardOutput = true;
             p.StartInfo.FileName = "c:/proj/OutputGenerator/bin/debug/OutputGenerator.exe";
             p.Start();
             p.StandardOutput.BaseStream.BeginRead(buffer, 0, 1, ProcessRead, null);
 
// our callback
        static byte[] buffer = new byte[1];
        static Process p;
        static void ProcessRead(IAsyncResult result)
        {
            p.StandardOutput.BaseStream.EndRead(result);
            // do something with the byte at buffer[0]
            p.StandardOutput.BaseStream.BeginRead(buffer, 0, 1, ProcessRead, null);
        }

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Fernando SotoRetiredCommented:
Hi themaniac;

Here is a code snippet of how to open a command line process/console and send it commands and receive the results in a multiline text box.

Fernando

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
 
namespace WindowsFormsApplication21
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        delegate void UpdateConsoleWindowDelegate(String msg);
        
        Process console = null;
        StreamWriter consoleStreamWriter = null;
 
        private void btnCreateConsole_Click(object sender, EventArgs e)
        {
            console = new Process();
            console.StartInfo.FileName = "cmd";
            console.StartInfo.Arguments = @"\K";
            console.StartInfo.UseShellExecute = false;
            console.StartInfo.CreateNoWindow = true;
            console.StartInfo.RedirectStandardInput = true;
            console.StartInfo.RedirectStandardOutput = true;
            // Set our event handler to asynchronously read the sort output.
            console.OutputDataReceived += new DataReceivedEventHandler(ConsoleOutputHandler);
            console.Start();
            // Use a stream writer to synchronously write the sort input.
            consoleStreamWriter = console.StandardInput;
            console.BeginOutputReadLine();
            btnCreateConsole.Enabled = false;
        }
 
        private void btnSend_Click(object sender, EventArgs e)
        {
            consoleStreamWriter.WriteLine(txtCommand.Text);
        }
 
        private void btnTerminate_Click(object sender, EventArgs e)
        {
            if (!console.HasExited)
            {
                console.Kill();
                console.Dispose();
                console = null;
                btnCreateConsole.Enabled = true;
            }
        }
 
        private void UpdateConsoleWindow(String message)
        {
            if (txtConsoleWindow.InvokeRequired)
            {
                UpdateConsoleWindowDelegate update = new UpdateConsoleWindowDelegate(UpdateConsoleWindow);
                txtConsoleWindow.Invoke(update, message);
            }
            else
            {
                txtConsoleWindow.AppendText(message);
            }
        }
 
        private void ConsoleOutputHandler(object sendingProcess,
            DataReceivedEventArgs recieved)
        {
            if( !String.IsNullOrEmpty(recieved.Data ))
            {                
                UpdateConsoleWindow(recieved.Data + "\r\nReady>");
            }
        }
 
    }
}

Open in new window

0
themaniacAuthor Commented:
Thank you very much both of you.You helped me a lot.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
.NET Programming

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.