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

Bit*_*lue 2 c# standards output

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

Console.WriteLine("blah blah");
Run Code Online (Sandbox Code Playgroud)

我想

Process p = Process.GetCurrentProcess();
StreamReader input = p.StandardOutput;
input.ReadLine();
Run Code Online (Sandbox Code Playgroud)

但它不起作用,因为第二行的“InvalidOperationException”。它说诸如“StandardOutput 未重定向,或进程尚未启动”之类的内容(已翻译)

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

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

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

Mor*_*iya 6

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

 // 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();
Run Code Online (Sandbox Code Playgroud)

来自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();
}
Run Code Online (Sandbox Code Playgroud)