Skip to content

Instantly share code, notes, and snippets.

@tommy-carlier
Created September 28, 2012 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tommy-carlier/3798818 to your computer and use it in GitHub Desktop.
Save tommy-carlier/3798818 to your computer and use it in GitHub Desktop.
Starting a process and capturing its output (C#)
using System;
using System.Diagnostics;
using System.Globalization;
namespace TC
{
/// <summary>Starts a process and allows capturing the output (both standard and error).</summary>
public static class ProcessStarter
{
/// <summary>Starts a new process with the specified file name and arguments.</summary>
/// <param name="fileName">The name of the file to start.</param>
/// <param name="arguments">The arguments to pass to the started application.</param>
/// <param name="standardOutputCallback">A callback function that is called when data is written to the standard output.</param>
/// <param name="errorOutputCallback">A callback function that is called when data is written to the error output.</param>
/// <returns>The exit code of the process.</returns>
/// <remarks>Both standardOutputCallback and errorOutputCallback can be null. In that case, the specified data is not captured.
/// The single argument to both these callback functions is the data that was written to the specified output.</remarks>
public static int StartProcess(
string fileName,
string arguments,
Action<string> standardOutputCallback,
Action<string> errorOutputCallback)
{
var startInfo = new ProcessStartInfo(fileName, arguments);
bool redirectStandard = standardOutputCallback != null;
bool redirectError = errorOutputCallback != null;
if (redirectStandard || redirectError)
{
// UseShellExecute has to be false if standard or error output is redirected
startInfo.UseShellExecute = false;
if (redirectStandard)
startInfo.RedirectStandardOutput = true;
if (redirectError)
startInfo.RedirectErrorOutput = true;
}
using (var process = new Process())
{
process.StartInfo = startInfo;
if (redirectStandard || redirectError)
{
// the events are only raised if this property is set to true
process.EnableRaisingEvents = true;
if (redirectStandard)
process.OutputDataReceived += (_, e) => standardOutputCallback(e.Data);
if (redirectError)
process.ErrorDataReceived += (_, e) => errorOutputCallback(e.Data);
}
process.Start();
// capturing standard output only starts if you call BeginOutputReadLine
if (redirectStandard)
process.BeginOutputReadLine();
// capturing error output only starts if you call BeginErrorReadLine
if (redirectError)
process.BeginErrorReadLine();
process.WaitForExit();
return process.ExitCode;
}
}
}
}
@apotox
Copy link

apotox commented Mar 24, 2018

Hi,
sadly, it not working for me , i used it to capture ngrok live output .

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment