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

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

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