Prevent a C# or VB.NET Console Application from closing when it finishes

Thoughts from the team
By    | June 8, 2010 | Bug of the Day,

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.

More like this