我有一个应用程序必须读取它自己的输出,该输出是通过
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/