【问题标题】:Repeatably Feeding Input to a Process' Standard Input可重复地将输入输入到过程的标准输入
【发布时间】:2011-10-06 23:25:27
【问题描述】:

我有一个维护状态的 (C#) 控制台应用程序。可以通过控制台向应用程序提供各种输入来更改状态。我需要能够为应用程序提供一些输入,然后读取输出冲洗并重复。

我创建了一个新进程并执行重定向输入/输出的所有正常工作。问题是,在我发送输入并在标准输出上调用ReadLine() 之后,在我在标准输入上调用Close() 之前它没有返回值,之后我无法再向输入流写入。

如何在接收输出的同时保持打开输入流?

 var process = new Process
                          {
                              StartInfo =
                                  {
                                      FileName =
                                          @"blabal.exe",
                                      RedirectStandardInput = true,
                                      RedirectStandardError = true,
                                      RedirectStandardOutput = true,
                                      UseShellExecute = false,
                                      CreateNoWindow = true,
                                      ErrorDialog = false
                                  }
                          };


        process.EnableRaisingEvents = false;

        process.Start();

        var standardInput = process.StandardInput;
        standardInput.AutoFlush = true;
        var standardOutput = process.StandardOutput;
        var standardError = process.StandardError;

        standardInput.Write("ready");
        standardInput.Close(); // <-- output doesn't arrive before after this line
        var outputData = standardOutput.ReadLine();

        process.Close();
        process.Dispose();

我从中重定向 IO 的控制台应用程序非常简单。它使用Console.Read() 从控制台读取并使用Console.Write() 写入它。我确定这些数据是可读的,因为我有另一个应用程序使用标准输出/输入(不是用 .NET 编写)从中读取数据。

【问题讨论】:

    标签: c# .net io-redirection


    【解决方案1】:

    发生这种情况是因为您使用的是Write("ready"),它将在文本中附加一个字符串,而不是使用WriteLine("ready")。就这么简单:)。

    【讨论】:

    • 不行!上帝,你是对的。如果我需要写一些没有前缀 \r\n 的东西怎么办?就像在它前面加上一个 '\n' 的 linux 风格。
    • @Qua:改用Environment.NewLineA string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms. 检查msdn
    • WriteLine 会自动使用 Enviroment.Newline 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多