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?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With