Wednesday, August 17, 2011

Running an Executable and Collecting the Output using C#

Sometimes you may need in the middle of a C# application you want to run an executable and collect the output.  Below sample of code will do what you want.. 

1. Simple method:

 

Process P = Process.Start("eyeDetect.exe", "hello1.jpg haarcascade_frontalface_alt.xml haarcascade_eye.xml");
P.StartInfo.UseShellExecute = false;
P.WaitForExit();
int result = P.ExitCode;
Console.WriteLine("Here is my result " + result);
Console.ReadLine(); 

2. Descriptive Method:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {         
        static void Main(string[] args)
        { 
            StringBuilder Output = new StringBuilder(); 
            using (Process proc = new Process())
                {
                    proc.StartInfo.FileName = "eyeDetect.exe";
                    proc.StartInfo.Arguments = "hello1.jpg haarcascade_frontalface_alt.xml haarcascade_eye.xml";
                    proc.StartInfo.UseShellExecute = false;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError = true;
                    proc.OutputDataReceived += (o, e) => Output.Append(e.Data).Append(Environment.NewLine);
                    proc.Start();
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();
                    proc.WaitForExit();
                    int ExitCode = proc.ExitCode;
                }
                Console.WriteLine(Output);
                Console.ReadLine();
        }
    }
}

1 comment: