vIceBerg
vIceBerg

Reputation: 4297

Capturing console stream input

I would like to make a console application (c# 3.5) which reads stream input.

Like this:

dir > MyApplication.exe

The app reads each line and outputs something to the console.

Which way to go?

Thanks

Upvotes: 4

Views: 9916

Answers (4)

Shahbaz Kiani
Shahbaz Kiani

Reputation: 11

A practice to add in your window app or any other type of integration is as below:

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();
}

Upvotes: 1

Mark Avenius
Mark Avenius

Reputation: 13947

It really depends on what you want to do and what type of stream you want to work with. Presumably, you are talking about reading a text stream (based on "the app reads each line..."). Therefore, you could 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 would derive of type System.IO.Stream (like FileStream, for example).

Upvotes: 0

user405725
user405725

Reputation:

You have to use a pipe (|) to pipe the output of the dir into the application. Redirect (>) that you have used in your example will trunk the file Application.exe and write the output of dir command there, thus, corrupting your application.

To read the data from the console, you have to use 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);   
   }
}

Upvotes: 4

Reed Copsey
Reed Copsey

Reputation: 564413

Use Console.Read/ReadLine to read from the standard input stream.

Alternatively, you can get direct access to the stream (as a TextReader) via Console.In.

Upvotes: 3

Related Questions