tags:

views:

2106

answers:

5

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?

+4  A: 

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>
Matthew Scharley
Does your example works for : echo "Foo bar baz" | ConsoleApplication1.exe | ConsoleApplication1.exe ?
Daok
Yes. Using a lower level analogy, what really happens with a pipe is the Stdout stream of the first application gets plugged into the Stdin stream of the next application in the pipeline. The console's stdin get put through the first application, and the last applications stdout is displayed.
Matthew Scharley
Tommorow I will try that!!! Thx :)
Daok
A: 

Here is something I have found with Google : Interprocess Communication but it requires kernell32.dll call... does it has an other way to do it? It's a simple task ...

Daok
IPC has nothing to do with pipes (not this sort anyway). Named pipes are something completely different again.
Matthew Scharley
ahhh didn't know!
Daok
Named pipes are used to setup communication between two programs who expect to communicate to each other (similar to an internal network afaik). Pipes in this sense are user defined communication channels, and the programs involved generally aren't even aware of the fact.
Matthew Scharley
Is it you that vote me down??? No need to go under 0 if it's not THE solution...
Daok
A: 

Console.In is a reference to a TextReader wrapped around the standard input stream. When piping large amounts of data to your program, it might be easier to work with that way.

Joel Mueller
A: 

there is a problem with supplied example.

  while ((s = Console.ReadLine()) != null)

will stuck waiting for input if program was launched without piped data. so user has to manually press any key to exit program.

Alex N