Keep console window of a new Process open after it finishes

It is easier to just capture the output from both the StandardOutput and the StandardError, store each output in a StringBuilder and use that result when the process is finished.

var sb = new StringBuilder();

Process p = new Process();

// redirect the output
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;

// hookup the eventhandlers to capture the data that is received
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.ErrorDataReceived += (sender, args) => sb.AppendLine(args.Data);

// direct start
p.StartInfo.UseShellExecute=false;

p.Start();
// start our event pumps
p.BeginOutputReadLine();
p.BeginErrorReadLine();

// until we are done
p.WaitForExit();

// do whatever you need with the content of sb.ToString();

You can add extra formatting in the sb.AppendLine statement to distinguish between standard and error output, like so: sb.AppendLine("ERR: {0}", args.Data);

Leave a Comment