SamKr
11/20/2014 - 2:10 PM

Launch a process and capture its output

Launch a process and capture its output

using (var process = new Process())
{
    process.StartInfo.FileName = "Taak.exe";
    process.StartInfo.Arguments = @"/parameter";
    process.StartInfo.UseShellExecute = false;
    process.StartInfo.RedirectStandardOutput = true;
    process.StartInfo.RedirectStandardError = true;

    var output = new StringBuilder();
    var error = new StringBuilder();

    using (var outputWaitHandle = new AutoResetEvent(false))
    using (var errorWaitHandle = new AutoResetEvent(false))
    {
        process.OutputDataReceived += (sender, e) => 
        {
            if (e.Data == null)
            {
                outputWaitHandle.Set();
            }
            else
            {
                output.AppendLine(e.Data);
            }
        };

        process.ErrorDataReceived += (sender, e) =>
        {
            if (e.Data == null)
            {
                errorWaitHandle.Set();
            }
            else
            {
                error.AppendLine(e.Data);
            }
        };

        var start = process.Start();

        if (!start)
        {
            Console.WriteLine("Taak kon niet gestart worden!");
        }

        process.BeginOutputReadLine();
        process.BeginErrorReadLine();

        if (process.WaitForExit(15000) && outputWaitHandle.WaitOne(15000) && errorWaitHandle.WaitOne(15000))
        {
            // Process voltooid.
        }
        else
        {
            // Timed out.
        }
    }
}