Bug 12551 - Console.ReadKey() when stdin is not coming from console different from .NET specified behavior
Summary: Console.ReadKey() when stdin is not coming from console different from .NET s...
Status: NEW
Alias: None
Product: Class Libraries
Classification: Mono
Component: mscorlib (show other bugs)
Version: 2.8.x
Hardware: PC Linux
: --- normal
Target Milestone: Untriaged
Assignee: Bugzilla
Depends on:
Reported: 2013-06-04 23:04 UTC by Greg Najda
Modified: 2013-06-09 17:32 UTC (History)
2 users (show)

See Also:
Is this bug a regression?: ---
Last known good build:


Description Greg Najda 2013-06-04 23:04:44 UTC
Running the following on .NET with stdin redirected:

C:\Users\Greg\Documents\Programming\consoletest\consoletest\bin\Debug>consoletest.exe < NUL
Press a key
InvalidOperationException thrown.

Running it on Mono in Linux:

greg@Kubuntu:~/dev/consoletest/consoletest/bin/Debug$ mono consoletest.exe < /dev/null
Press a key
Key pressed: 0

greg@Kubuntu:~/dev/consoletest/consoletest/bin/Debug$ mono --version
Mono JIT compiler version (Debian

The documentation on MSDN (http://msdn.microsoft.com/en-us/library/x3h8xffw.aspx) clearly states that InvalidOperationException should be thrown if "The In property is redirected from some stream other than the console."

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace consoletest
    class Program
        static void Main(string[] args)
            Console.WriteLine("Press a key");
            bool exceptionThrown = false;
            ConsoleKeyInfo key = new ConsoleKeyInfo();
                key = Console.ReadKey(intercept: true);
            catch (InvalidOperationException)
                // This is the documented behavior when reading from a non-console stdin
                Console.WriteLine("InvalidOperationException thrown.");
                exceptionThrown = true;
            if (!exceptionThrown)
                // Mono instead returns a ConsoleKeyInfo with a Key value of 0.
                Console.WriteLine("Key pressed: {0}", (int)key.Key);
Comment 1 Jonathan Pryor 2013-06-05 09:37:03 UTC
Probably related: Bug #10106.
Comment 2 Greg Najda 2013-06-09 17:32:25 UTC
Looking at the code, the fix appears to be simply having NullConsoleDriver.ReadKey(bool intercept) throw an InvalidOperationException instead of returning ConsoleKeyInfo.Empty.

Note You need to log in before you can comment on or make changes to this bug.