Blam
Blam

Reputation: 2965

Redirecting console output to another application

So say I run my program:

Process proc = new Process();
proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath)
                           + @"\Console.exe";
proc.Start();

And then wish to output my console stream to this application, how would I go about doing so? So say I have:

Console.WriteLine("HEY!");

I want that to show up in program that I ran's console. I know I have to redirect the output using

Console.SetOut(TextWriter);

But I have no idea how I would go about making it write to the other program.

I can see how I could do it if I were running my main program from Console.exe using RedirectStandardInput.. but that doesn't really help :P

Upvotes: 3

Views: 6815

Answers (3)

stevemegson
stevemegson

Reputation: 12093

RedirectStandardInput makes Console.exe take its input from a stream which you can access in the main program. You can either write directly to that stream, or use SetOut to redirect console output there...

Process proc = new Process();
proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath)
                       + @"\Console.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.Start();

proc.StandardInput.WriteLine("Hello");

Console.SetOut(proc.StandardInput);
Console.WriteLine("World");

EDIT

It's possible that Console.exe doesn't cope well with having data piped into it rather than entered interactively. You could check this from the command line with something like

echo "Hello" | Console.exe

If that doesn't do what you expect, redirecting your program's output won't either. To test your program without worrying about the target program, you could try

proc.StartInfo.FileName = @"cmd";
proc.StartInfo.Arguments = @"/C ""more""";

If that displays the text that you write to it, then the problem is on the receiving end.

Upvotes: 2

James Curran
James Curran

Reputation: 103485

RedirectStandardInput isn't the problem. Console is the problem.

 StreamWriter myConsole = null;
if (redirect)
{
 Process proc = new Process(); 
 proc.StartInfo.FileName = Path.GetDirectoryName(Application.ExecutablePath) 
                       + @"\Console.exe"; 
 proc.StartInfo.UseShellExecute = false;
 proc.StartInfo.RedirectStandardInput = true;
 proc.Start(); 
 myConsole = myProcess.StandardInput;
 }
 else
    myConsole = Console.Out;

Then just use myConsole as you would Console.

Upvotes: 1

Icemanind
Icemanind

Reputation: 48686

You need to use Process.StandardOutput and Process.StandardInput. Check out this article from MSDN, which may help point you into the right direction: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

By the way, a much easier way to do what you are doing can be found here, as an accepted answer to a similar SO question: c# redirect (pipe) process output to another process

Upvotes: 0

Related Questions