Redirecting console output to another application

Say I ran my program:

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

And then you want to output my console stream to this application, how would I do it? So say that I have:

Console.WriteLine("HEY!");

I want this to appear in the program in which I started the console. I know that I need to redirect the output using

Console.SetOut(TextWriter);

But I have no idea how I'm going to record in another program.

I can figure out how to do this if I run my main program from Console.exe using RedirectStandardInput .. but this does not help: P

+3
source share
3 answers

RedirectStandardInput Console.exe , . , SetOut ...

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");

, Console.exe , .

echo "Hello" | Console.exe

, , . , ,

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

, , .

+2

RedirectStandardInput . Console - .

 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;

myConsole, Console.

+1

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

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

0
source

Source: https://habr.com/ru/post/1760360/


All Articles