I am trying to catch the output from a child console app.
- When the parent is a console app everything works.
- When the parent is a windows app then the child fails to run with an exception from
Console.ReadKey()
saying there is no way to readKey when the stdInput has been redirected. However, I am not redirecting the input (only the output).
What am I missing here?
Child Code (set project to console app):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ChildProcess
{
internal class Program
{
private static void Main(string[] args)
{
char key = Console.ReadKey().KeyChar;
Console.Out.WriteLine("stdout");
Console.Error.WriteLine("stderr");
}
}
}
Parent app code: (set project to windows app)
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RedirectProcessOutput
{
internal class Program
{
private static void Main(string[] args)
{
string fileName = @"ChildPRocess.exe";
string arg = "i";
string processOutput = "?";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = false;
p.StartInfo.FileName = fileName;
p.StartInfo.Arguments = arg;
p.Start();
processOutput = p.StandardOutput.ReadToEnd();
p.WaitForExit();
Console.WriteLine("The child process output is:" + processOutput);
}
}
}
I was expecting the application to run without crashing even when the parent is a window app since the child should have its own console and I am not redirecting the input for that. BTW - everything works when:
- the child is not doing a "ReadKey" or
- the parent is not redirecting stdout at all