I’m working on a little console application to run a scheduled data import task. During the debugging of the application I wanted the console window to remain open after the program had finished executing – by default it closes when the application finishes. There seem to be two common answers to this problem.
The first solution is to run the application without debugging by using Ctrl+F5 instead of just F5. The console window will remain open when the program has finished. The disadvantage of this is that you lose Visual Studio’s debug information.
The second solution is to add a couple lines of code to the end of your Main() method which halts the application until the user presses a key. This allows you to run in Visual Studio’s Debug mode but requires a change to the code that you might not want in a production environment.
Console.WriteLine("Press any key to close");
Console.ReadKey();
Neither solution is perfect, but they both solve the problem well enough to let me get on with development.
You can always put #if debug preprocessor directive or detect if debugger is attached to the process and then execute the last 2 lines of code
#if DEBUG
Console.WriteLine(“Press any key to close”);
Console.ReadKey();
#endif
OR
There is a IsDebuggerAttached static property. I am not sure if it is in Process or Application. Either way, you could put an if condition such as:
if (Application.IsDebuggerAttached)
{
Console.WriteLine(“Press any key to close”);
Console.ReadKey();
}
Thanks Raghu, that’s a great idea!
using System.Diagnostics;
if (Debugger.IsAttached) Debugger.Break();
Will halt execution, leaving the console window open.
Another great tip, thanks Nikki!
What about Ctrl+F5? If you start console app with this key combination console app won’t be closed when it finishes.
Sorry.. didn’t read all the article, just saw the code %-)