Tip : Flush the keyboard buffer from C#

Here’s another tip from an MSDN forum discussion. Someone wanted to know how to flush the keyboard buffer in a C# console application.

Here’s a simple hack to do this :

private static void FlushKeyboard()
    while (Console.In.Peek() != -1)

Now you can use it as follows :

char x = (char)Console.Read();
char y = (char)Console.Read();
Console.WriteLine("{0}, {1}", x, y);

Even if you enter more than a single character after the first call to Read(), the second Read() will not be affected.


2 thoughts on “Tip : Flush the keyboard buffer from C#

  1. It is really useful for resolving
    System.FormatException :
    “Input string was not in a correct format.”

    where we try to repeatedly excute code like
    Console.WriteLine(“Please press enter key”);
    intA = int.Parse(Console.ReadLine());
    intB = int.Parse(Console.ReadLine());

  2. Thank you, for this solution.

    I was looking for something like that, the only thing i changed was Console.In.Read() for this Console.In.ReadLine() becouse I needed for readline and worked like a charm!

    Grettings from Mexico!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s