Reading process output

Here is my little example about how to catch run console program and catch the output. I used similar code to read the output of OpenSLL.

public string RunProcess(string path, string args)
{
   
ProcessStartInfo proc = new ProcessStartInfo
(path, args);
    proc.RedirectStandardOutput =
true
;
    proc.UseShellExecute =
false
;

   
Process p = Process
.Start(proc);
    p.Start();

   
while
(!p.HasExited)
        System.Threading.
Thread
.Sleep(100);

   
string
s = p.StandardOutput.ReadToEnd();
    p.Dispose();
   
return s;
}

This is the simplest version of process output catching method. You may need also return code of process to verify that process succeeded. In this case we can extend our code by adding process result class and returning it instead of output string.

public class ProcessResult
{
   
public int ReturnCode { get; set
; }
   
public string Output { get; set
; }
}

private ProcessResult RunProcess(string path, string
args)
{
   
ProcessStartInfo proc = new ProcessStartInfo
(path, args);
    proc.RedirectStandardOutput =
true
;
    proc.UseShellExecute =
false
;

   
Process p = Process
.Start(proc);
    p.Start();

   
while
(!p.HasExited)
        System.Threading.
Thread
.Sleep(100);

   
ProcessResult result = new ProcessResult
();
    result.ReturnCode = p.ExitCode;
    result.Output = p.StandardOutput.ReadToEnd();
    p.Dispose();
   
return result;
}

Happy processing! :)

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

    Your email address will not be published. Required fields are marked *