How to read "Enter" from the keyboard to exit program

Aaron L. W- Gabriel picture Aaron L. W- Gabriel · Sep 18, 2015 · Viewed 25.7k times · Source

I have written a simple program in C# in Visual Studio 2013. At the end of my program I instruct the user to:

"Please Press Enter to Exit the Program."

I would like to get the input from the keyboard on the next line and if ENTER is pressed, the program will quit.

Can anyone tell me how I can achieve this function?

I have tried the following code:

Console.WriteLine("Press ENTER to close console......");
String line = Console.ReadLine();

if(line == "enter")
{
    System.Environment.Exit(0);
}

Answer

DogeAmazed picture DogeAmazed · Sep 18, 2015

Try following:

ConsoleKeyInfo keyInfo = Console.ReadKey();
while(keyInfo.Key != ConsoleKey.Enter)
    keyInfo = Console.ReadKey();

You can use a do-while too. More informations: Console.ReadKey()