Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
437 views
in Technique[技术] by (71.8m points)

c# - How to read standard output of my own application

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...