Skip to content

Instantly share code, notes, and snippets.

@msugakov
Created May 5, 2016 17:57
Show Gist options
  • Save msugakov/08da3044b899b86d8af316f8e426a485 to your computer and use it in GitHub Desktop.
Save msugakov/08da3044b899b86d8af316f8e426a485 to your computer and use it in GitHub Desktop.
public static int ExecuteProcess(
string fileName,
string arguments,
int timeout,
out string standardOutput,
out string standardError)
{
int exitCode;
var standardOutputBuilder = new StringBuilder();
var standardErrorBuilder = new StringBuilder();
using (var process = new Process())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.FileName = fileName;
process.StartInfo.Arguments = arguments;
process.OutputDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardOutputBuilder.AppendLine(args.Data);
}
};
process.ErrorDataReceived += (sender, args) =>
{
if (args.Data != null)
{
standardErrorBuilder.AppendLine(args.Data);
}
};
process.Start();
// This is our place of interest
process.BeginOutputReadLine();
process.BeginErrorReadLine();
if (process.WaitForExit(timeout))
{
process.WaitForExit(); // <-- this makes sure that streams flushed
exitCode = process.ExitCode;
}
else
{
process.Kill();
throw new TimeoutException("Process wait timeout expired");
}
}
standardOutput = standardOutputBuilder.ToString();
standardError = standardErrorBuilder.ToString();
return exitCode;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment