Console input stream empty or not?

This is making me grumpy so I’m going to share and see if this eventually (assuming I find a solution) serves as a place where others don’t run into what I’ve been struggling with. It would seem to be a simple problem but I haven’t been able to figure it out in a way that feels right (i.e., I have it “working” but just not convinced it’s done “right.”).


Detect whether or not there are any characters in the input stream to a console application when it starts up. I.e., has some data been piped to it or not.

My current solution:

bool IsThereSomethingThere()
        return Console.KeyAvailable;
    catch (InvalidOperationException)
        // There is something in the input stream

    return true;

How does it work?

Console.KeyAvailable throws an InvalidOperationException if the standard input is redirected to something other than the keyboard. In the cases where output from another command/application is piped to the console app it will throw the exception. If nothing has been piped to it, it happily returns false and moves on just fine.

My dilemma

I’m having a hard time believing the only way to do this is by expecting an exception–that never sounds good to me. Problem is I’ve tried a few other ways that would seem to have had a good chance at working (such as the various other Console methods available like Peek(), Read*(), etc.) but none work. Peek, for example, should return a -1 when there are no more characters in the buffer but it’s actually blocking for me (i.e., it’s waiting for input instead of just coming back to me with a -1).

I’m sure I’m missing something simple so I ended up doing a few searches and found a few that were having similar problems but no answers. At this point, I guess I’ll sleep on it and see how it goes tomorrow but if anyone knows better I’d certainly appreciate a clue.

2 thoughts on “Console input stream empty or not?

  1. Okay, thanks Jezell. I had been avoiding having to go to pinvoke (assuming there was a vanilla mgd way) but I’ll give it a try. Thanks again.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.