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
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);
}
}
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.
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();
}
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).
精彩评论