Keep console window of a new Process open after it finishes

I currently have a portion of code that creates a new Process and executes it from the shell.

Process p = new Process();
...
p.Start();
p.WaitForExit();

This keeps the window open while the process is running, which is great. However, I also want to keep the window open after it finishes to view potential messages. Is there a way to do this?


Solution 1:

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);

Solution 2:

This will open the shell, start your executable and keep the shell window open when the process ends

Process p = new Process();
ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
p.StartInfo = psi;
p.Start();
p.WaitForExit();

or simply

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = "CMD.EXE";
psi.Arguments = "/K yourmainprocess.exe";
Process p = Process.Start(psi);
if(p != null && !p.HasExited)
    p.WaitForExit();

Solution 3:

Be carefull espacially on switch /k, because in many examples is usually used /c.

CMD /K Run Command and then return to the CMD prompt.

CMD /C Run Command and then terminate

var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/k yourmainprocess.exe";
p.Start();
p.WaitForExit();