Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Console receive input with pipe

Tags:

c#

pipe

I know how to program Console application with parameters, example : myProgram.exe param1 param2.

My question is, how can I make my program works with |, example : echo "word" | myProgram.exe?

like image 698
Patrick Desjardins Avatar asked Oct 14 '08 00:10

Patrick Desjardins


2 Answers

You need to use Console.Read() and Console.ReadLine() as if you were reading user input. Pipes replace user input transparently. You can't use both easily (although I'm sure it's quite possible...).

Edit:

A simple cat style program:

class Program {     static void Main(string[] args)     {         string s;         while ((s = Console.ReadLine()) != null)         {             Console.WriteLine(s);         }      } } 

And when run, as expected, the output:

 C:\...\ConsoleApplication1\bin\Debug>echo "Foo bar baz" | ConsoleApplication1.exe "Foo bar baz"  C:\...\ConsoleApplication1\bin\Debug> 
like image 133
Matthew Scharley Avatar answered Oct 03 '22 22:10

Matthew Scharley


The following will not suspend the application for input and works when data is or is not piped. A bit of a hack; and due to the error catching, performance could lack when numerous piped calls are made but... easy.

public static void Main(String[] args) {      String pipedText = "";     bool isKeyAvailable;      try     {         isKeyAvailable = System.Console.KeyAvailable;     }     catch (InvalidOperationException expected)     {         pipedText = System.Console.In.ReadToEnd();     }      //do something with pipedText or the args } 
like image 26
CodeMiller Avatar answered Oct 03 '22 21:10

CodeMiller