Last active
September 30, 2015 15:18
-
-
Save jhgbrt/1815567 to your computer and use it in GitHub Desktop.
C#/.Net class for launching a CommandLine process and capturing stdout/stderr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class ProcessHelper | |
{ | |
/// <summary> | |
/// Starts a command line process, redirecting both StdOut and StdErr. | |
/// </summary> | |
/// <param name="fileName">Path to the executable</param> | |
/// <param name="arguments">Command line arguments</param> | |
/// <param name="onErr">Action to perform when data from the child process is read from StdErr. The action takes 2 parameters: a Process instance (representing the child process) and a string (the data it wrote to StdErr)</param> | |
/// <param name="onOut">Action to perform when data from the child process is read from StdOut. The action takes 2 parameters: a Process instance (representing the child process) and a string (the data it wrote to StdOut)</param> | |
/// <returns></returns> | |
public static Process StartCommandLine(string fileName, string arguments, Action<Process, string> onErr, Action<Process, string> onOut) | |
{ | |
var process = new Process | |
{ | |
StartInfo = new ProcessStartInfo | |
{ | |
FileName = fileName, | |
Arguments = arguments, | |
RedirectStandardError = true, | |
RedirectStandardOutput = true, | |
UseShellExecute = false | |
}, | |
EnableRaisingEvents = true | |
}; | |
process.ErrorDataReceived += (s, e) => onErr(s as Process, e.Data); | |
process.OutputDataReceived += (s, e) => onOut(s as Process, e.Data); | |
process.Start(); | |
process.BeginErrorReadLine(); | |
process.BeginOutputReadLine(); | |
return process; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment