Reputation: 14075
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.
Upvotes: 2
Views: 3402
Reputation: 7906
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();
}
Upvotes: 5