How to read standard output of my own application

血红的双手。 提交于 2019-12-10 11:56:49

问题


I have an application that must read it's own output that is written via

Console.WriteLine("blah blah");

I'm trying

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

But it doesn't work because of "InvalidOperationException" at the second line. It says something like "StandardOutput wasn't redirected, or the process has not been started yet" (translated)

How can I read my own output ? Is there another way to do that ? And to be complete how to write my own input ?

The application with the output is running already.

I want to read it's output live in the same application. There is no 2nd app. Only one.


回答1:


I'm just guessing as to what your intention might be but if you want to read the output from a application you started you can redirect the output.

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

example from http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

Edit:

If you want to redirect the output of your current console application as your edit specifies you can use.

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


来源:https://stackoverflow.com/questions/14192699/how-to-read-standard-output-of-my-own-application

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!