c# - 如何读取我自己的应用程序的标准输出

标签 c# standards output

我有一个应用程序必须读取它自己的输出,该输出是通过

Console.WriteLine("blah blah");

我在努力

Process p = Process.GetCurrentProcess();
StreamReader input = p.StandardOutput;
input.ReadLine();

但由于第二行的“InvalidOperationException”,它不起作用。它说类似“StandardOutput 未重定向,或者进程尚未启动”(已翻译)

如何读取自己的输出?还有另一种方法吗?并完成如何编写我自己的输入?

具有输出的应用程序已经在运行。

我想阅读它的输出在同一个应用程序中。没有第二个应用程序。只有一个。

最佳答案

我只是猜测您的意图可能是什么,但如果您想从您启动的应用程序中读取输出,您可以重定向输出。

 // Start the child process.
 Process p = new Process();
 // Redirect the output stream of the child process.
 p.StartInfo.UseShellExecute = false;
 p.StartInfo.RedirectStandardOutput = true;
 p.StartInfo.FileName = "Write500Lines.exe";
 p.Start();
 // Do not wait for the child process to exit before
 // reading to the end of its redirected stream.
 // p.WaitForExit();
 // Read the output stream first and then wait.
 string output = p.StandardOutput.ReadToEnd();
 p.WaitForExit();

示例来自 http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

编辑:

如果您想按照您的编辑指定重定向当前控制台应用程序的输出,您可以使用。

private static void Main(string[] args)
{
    StringWriter writer = new StringWriter();
    Console.SetOut(writer);
    Console.WriteLine("hello world");

    StringReader reader = new StringReader(writer.ToString());
    string str = reader.ReadToEnd();
}

关于c# - 如何读取我自己的应用程序的标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14192699/

相关文章:

javascript - AsyncFunction 未定义,但 MDN 记录了它的用法

c++ - 二维数组的行为

c++ - 简单的 C++ 控制台 I/O 问题

c# - 具有许多扩展的 OpenFileDialog

c# - 如何在没有调用的情况下合并两个 C# Lambda 表达式?

c# - 启动时启动应用程序,使用错误的路径加载

c# - 获取对象处置/销毁的通知

c++ - 如果比较函数不是运算符 <,为什么 std::sort 会崩溃?

c++ - 比较指向不同数组的指针是否相等是未指定的行为吗?

java - 从 HashMap 中获取特定数据