Capture console input stream

I would like to create a console application (C # 3.5) that reads stream input.

Like this:

dir> MyApplication.exe

The application reads each line and displays something on the console.

How?

thanks

+4
source share
4 answers

You must use the pipe ( | ) to output the dir output to the application. The redirect ( > ) that you used in your example will connect the Application.exe file and write the output of the dir command there, thus damaging your application.

To read data from the console, you must use the Console.ReadLine method, for example:

 using System; public class Example { public static void Main() { string line; do { line = Console.ReadLine(); if (line != null) Console.WriteLine("Something.... " + line); } while (line != null); } } 
+4
source

Use console. Read / ReadLine for reading from a standard input stream.

Alternatively, you can directly access the stream (like TextReader) through Console.In .

+3
source

The practice of adding to your windowed application or any other type of integration:

 static public void test() { System.Diagnostics.Process cmd = new System.Diagnostics.Process(); cmd.StartInfo.FileName = "cmd.exe"; cmd.StartInfo.RedirectStandardInput = true; cmd.StartInfo.RedirectStandardOutput = true; cmd.StartInfo.CreateNoWindow = true; cmd.StartInfo.UseShellExecute = false; cmd.Start(); /* execute "dir" */ cmd.StandardInput.WriteLine("dir"); cmd.StandardInput.Flush(); cmd.StandardInput.Close(); string line; int i = 0; do { line = cmd.StandardOutput.ReadLine(); i++; if (line != null) Console.WriteLine("Line " +i.ToString()+" -- "+ line); } while (line != null); } static void Main(string[] args) { test(); } 
+1
source

It really depends on what you want to do and what type of stream you want to work on. Presumably, you're talking about reading a text stream (based on "application reads each line ..."). So you can do something like this:

  using (System.IO.StreamReader sr = new System.IO.StreamReader(inputStream)) { string line; while (!string.IsNullOrEmpty(line = sr.ReadLine())) { // do whatever you need to with the line } } 

Your inputStream will output the type System.IO.Stream (e.g. FileStream, for example).

0
source

All Articles