Created
May 5, 2016 17:57
-
-
Save msugakov/08da3044b899b86d8af316f8e426a485 to your computer and use it in GitHub Desktop.
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 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