Friday, February 1, 2013

Helper for System.Diagnostics.Process

It's one thing to kick off a process from C# using Process.Start out of System.Diagnostics.  Nothing to that.  But what if you want to send the process some input beyond the arguments?  Or you want to perform processing on the output is sends to the console?



This code provides that help.

Just call ProcessHelper.Start.

The delegates for output and error provide a mechanism for processing each line of output.  The delegate will be called for each line produced.


This code below provides a simple example of how to use the ProcessHelper.  Each line of output is simply added to the StringBuilder objects.




StringBuilder outData = new StringBuilder();
StringBuilder errData = new StringBuilder();

System.Diagnostics.Process p = ProcessHelper.Start("MyProcess.exe", "arg1 arg2 arg3", "Standard Input Data",
        delegate(string parm)
        {
            outData.AppendLine(parm);
        },
        delegate(string parm)
        {
            errData.AppendLine(parm);
        }
);

p.WaitForExit();