Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep console window of a new Process open after it finishes

Tags:

c#

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?

like image 962
Jon Martin Avatar asked May 28 '14 20:05

Jon Martin


People also ask

How do I keep the console window open?

Run Application Without Debugging To Keep Console Window Open. To keep the console window open in Visual Studio without using the Console. ReadLine() method, you should run the application without debug mode by pressing Ctrl+F5 or by clicking on the menu Debug > Start without Debugging option.

How do I stop my console from closing in C#?

Try Ctrl + F5 in Visual Studio to run your program, this will add a pause with "Press any key to continue..." automatically without any Console.

How do I close the console window?

To close or exit the Windows command line window, also referred to as command or cmd mode or DOS mode, type exit and press Enter . The exit command can also be placed in a batch file. Alternatively, if the window is not fullscreen, you can click the X close button in the top-right corner of the window.


1 Answers

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

like image 52
rene Avatar answered Sep 20 '22 16:09

rene