2010-10-06 83 views
4

我想制作一个控制台应用程序(c#3.5),它读取流输入。捕获控制台流输入

像这样:

DIR> MyApplication.exe

该应用程序读出每一行并输出的东西到控制台。

要走哪条路?

谢谢

+0

你究竟有什么困难? – Oded 2010-10-06 15:04:19

回答

4

您必须使用管道(|)将dir的输出传送到应用程序中。您在示例中使用的重定向(>)将中继文件Application.exe并在那里写入dir命令的输出,从而破坏您的应用程序。

读取从控制台的数据,你必须使用Console.ReadLine方法,例如:

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); 
    } 
} 
+0

Arrrggg ...管道而不是重定向...你有钥匙... – vIceBerg 2010-10-06 15:09:40

3

使用控制台。 Read/ReadLine从标准输入流中读取。

或者,您可以通过Console.In直接访问流(作为TextReader)。

0

这真的取决于你想要做什么,你要使用什么类型的流。据推测,你正在讨论阅读文本流(基于“该应用程序读取每一行......”)。因此,你可以做这样的事情:

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 
     } 
    } 

你的inputStream将获得型System.IO.Stream的(像的FileStream,例如)。

1

的一个练习,在窗口的应用程序添加或任何其他类型的集成是如下:

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