Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# -- Console.In.ReadToEnd() hangs on user input if no data piped to program

I'm writing a C# console application that takes 2 parameters: myprogram.exe param1 param2

param2 is optional, and the idea is if it's not present, get piped data:

echo "hithere" | myprogram.exe param1

I've made this part work by capturing Console.In.ReadToEnd() when only 1 parameter is passed.

The problem I'm facing is when only 1 parameter is passed and no data is piped, it just sits there listening to user input and the only way to close out is to Ctrl+C to end the program.

Instead, is there a way to return an error and quit the program if only 1 parameter was supplied and no data was piped ?


To test if there is anything waiting, I've tried using:

  • Console.OpenStandardInput().CanRead
  • Console.OpenStandardInput().Length
  • Console.In.Peek()

That didn't work.

I've also tried the 'hack' mentioned at the bottom of this stackoverflow question: C# Console receive input with pipe .

Any ideas?

like image 708
Matt Avatar asked Dec 11 '10 23:12

Matt


People also ask

What do you mean by C?

C is an imperative procedural language supporting structured programming, lexical variable scope, and recursion, with a static type system. It was designed to be compiled to provide low-level access to memory and language constructs that map efficiently to machine instructions, all with minimal runtime support.

What is the full name of C?

In the real sense it has no meaning or full form. It was developed by Dennis Ritchie and Ken Thompson at AT&T bell Lab. First, they used to call it as B language then later they made some improvement into it and renamed it as C and its superscript as C++ which was invented by Dr.

Is C language easy?

Compared to other languages—like Java, PHP, or C#—C is a relatively simple language to learn for anyone just starting to learn computer programming because of its limited number of keywords.

What is %d in C programming?

In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.


1 Answers

Instead of checking the console, check the command line. If they pass in enough arguments, then assume there is nothing to get from the console. If they don't specify enough parameters then assume the URL is going to come from the console. You don't need to use ReadToEnd(), just use ReadLine() instead so you can go line by line. If you use ReadToEnd() you'll have to hit CTRL+Z (or CTRL+D in linux) to indicate the end of the input stream.

like image 109
OJ. Avatar answered Sep 27 '22 23:09

OJ.