How to read from a file in command line arguments otherwise standard? (emulate Python file system)

I want my application to read the files specified in the command line argument or with the standard one, so the user can use its myprogram.exe data.txt or otherprogram.exe | myprogram.exe otherprogram.exe | myprogram.exe . How to do it in C #?


In Python, I will write

 import fileinput for line in fileinput.input(): process(line) 

This iterates over the lines of all files listed in sys.argv [1:], by default for sys.stdin, if the list is empty. If the file name is '-', it is also replaced with sys.stdin.

Perl <> and Ruby ARGF also useful.

+4
source share
4 answers

stdin displayed as TextReader through Console.In . Just declare the TextReader variable for input, which either uses Console.In or the file of your choice and uses it for all your input operations.

 static TextReader input = Console.In; static void Main(string[] args) { if (args.Any()) { var path = args[0]; if (File.Exists(path)) { input = File.OpenText(path); } } // use `input` for all input operations for (string line; (line = input.ReadLine()) != null; ) { Console.WriteLine(line); } } 

Otherwise, if refactoring to use this new variable is too expensive, you can always redirect Console.In to your file using Console.SetIn() .

 static void Main(string[] args) { if (args.Any()) { var path = args[0]; if (File.Exists(path)) { Console.SetIn(File.OpenText(path)); } } // Just use the console like normal for (string line; (line = Console.ReadLine()) != null; ) { Console.WriteLine(line); } } 
+6
source

It's terribly simple, really.

In the C # code editor, you can:

 public static void Main(string[] args) { //And then you open up a file. using(Streamreader sr = new Streamreader(args[0])) { String line = sr.ReadToEnd(); Console.WriteLine(line); } } 

Another good idea is to iterate over the args elements in the C # collection so that you can accept multiple files as input. Example: main.exe file1.txt file2.txt file3.txt , etc.

You would do this by modifying the above code using a special for loop, for example:

 foreach(string s in args) { using( Streamreader sr = new Streamreader(s) ) { String line = sr.ReadToEnd(); Console.WriteLine(line); } } 

Good luck

+3
source

use

  static void Main(string[] args) 

and then iterate over each input using args.length in a for-loop, for example.

usage example: http://www.dotnetperls.com/main

0
source

Try the following:

 public void Main(string[] args) { if (args.Count() > 0) { byte[] byteArray = Encoding.UTF8.GetBytes(args[0]); MemoryStream stream = new MemoryStream(byteArray); StreamReader sr = new StreamReader(stream); String line = sr.ReadToEnd(); Console.WriteLine(line); } Console.ReadLine(); } 

args [0] is a string that must be converted to a stream before passing to the StreamReader constructor.

0
source

Source: https://habr.com/ru/post/1438284/


All Articles