Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 捕获控制台流输入_C#_Input_Console_Stream - Fatal编程技术网

C# 捕获控制台流输入

C# 捕获控制台流输入,c#,input,console,stream,C#,Input,Console,Stream,我想制作一个控制台应用程序(c#3.5),用于读取流输入 像这样: dir>MyApplication.exe 应用程序读取每一行并向控制台输出内容 走哪条路 谢谢使用Console./读取标准输入流 或者,您可以通过直接访问流(作为文本阅读器)。您必须使用管道(|)将目录的输出通过管道输送到应用程序中。您在示例中使用的重定向()将对文件Application.exe进行中继,并将dir命令的输出写入其中,从而损坏您的应用程序 要从控制台读取数据,必须使用方法,例如: using System;

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

像这样:

dir>MyApplication.exe

应用程序读取每一行并向控制台输出内容

走哪条路

谢谢

使用Console./读取标准输入流

或者,您可以通过直接访问流(作为文本阅读器)。

您必须使用管道(
|
)将
目录的输出通过管道输送到应用程序中。您在示例中使用的重定向(
)将对文件
Application.exe
进行中继,并将
dir
命令的输出写入其中,从而损坏您的应用程序

要从控制台读取数据,必须使用方法,例如:

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

这实际上取决于您想要做什么,以及您想要使用什么类型的流。您可能正在谈论阅读文本流(基于“应用程序读取每行…”)。因此,您可以这样做:

    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)。

在Windows应用程序或任何其他类型的集成中添加的实践如下所示:

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

你到底有什么困难?