0

I'm trying to read in a text file from the command prompt in C#, via

program.exe < textfile.txt 

However, I cannot find the correct way to do this.

So far, I've only been able to pass the path and the filename to string [] args and then opening the file with the StreamReader class. While this is an acceptable alternative, I've been told that the method with "<", which I suppose is a redirection of standard input, offers advantages like not requiring file handling.

Can anyone give some insight into this?

edit: Program.exe is my C# application.

Fang
  • 2,199
  • 4
  • 23
  • 44
  • 1
    I believe it's the same as [this question](http://stackoverflow.com/questions/199528), but with the input coming from a file rather than the result of a different command – D Stanley Jan 19 '16 at 22:29
  • 1
    Have you tried Console.ReadLine()? – Codism Jan 19 '16 at 22:29
  • 1
    If program.exe is your C# program (it is not clear) then you'd use Console.ReadLine(). Advantages, hmm, no. Debugging sucks. – Hans Passant Jan 19 '16 at 22:29
  • Thanks guys. I guess I missed the most obvious answer to the problem, which is indeed Console.ReadLine(). – Fang Jan 19 '16 at 22:32

2 Answers2

2

You've got the right idea - the '<' symbol means the Console class reads from the file you specify, instead of reading user input from the console. When you do this, you read from it using the Console class.

The advantages of reading from STDIN is that the user can either run the program as program.exe, and manually type the input the program is expecting, or they can run it as program.exe < input.txt. The only time this is a disadvantage is if you know you will always supply a file, and consider the effort of typing the '<' symbol too much...

Andrew Williamson
  • 8,299
  • 3
  • 34
  • 62
2

In a command prompt the < sign is one of several redirection operators. Specifically, the < sign is the input redirection operator. When you type this: program.exe < textfile.txt, you are telling the command prompt to execute program.exe and read the command input from a file, instead of reading input from the keyboard. In this way, the command prompt basically opens textfile.txt and takes its content and "stuffs it" into the keyboard buffer, so, as far as program.exe is concerned, the input is being read from the keyboard and has no idea you are actually "stuffing" the keyboard buffer with contents from a file.

If your program currently is reading from a file, you will need to modify your program. You no longer want to read from a file and instead read from the keyboard, using commands such as Console.ReadLine or Console.Read or Console.ReadKey.

As far as advantages, the advantages are minimal.

Icemanind
  • 47,519
  • 50
  • 171
  • 296