I am writing an application in C# that at some point starts an application as a child process using the Process class with Asynchronous IO redirection as shown below:
private void AppLaunch_Click(object sender, RoutedEventArgs e)
{
Process appProcess = new Process();
appProcess.StartInfo.FileName = currAppPath;
appProcess.StartInfo.Arguments = "";
//Setup Redirection
appProcess.StartInfo.UseShellExecute = false;
appProcess.StartInfo.ErrorDialog = false;
appProcess.StartInfo.RedirectStandardError = true;
appProcess.EnableRaisingEvents = true;
// Attach Output Handler
appProcess.ErrorDataReceived += appProc_DataReceived;
appProcess.Exited += appProc_Exited;
buildLogConsoleOutputTxtbox.AppendText(currAppPath + "\n");
appProcess.Start();
appProcess.BeginErrorReadLine();
}
private void appProc_DataReceived(object sender, DataReceivedEventArgs e)
{
if (!String.IsNullOrEmpty(e.Data))
{
this.appendLogText(e.Data);
}
}
private void appProc_Exited(object sender, System.EventArgs e)
{
Process proc = (Process)sender;
// Wait a short while to allow all console output to be processed and appended
Thread.Sleep(40);
this.appendLogText("\n>>");
proc.Close();
}
private void appendLogText(string logText)
{
// Use a delegate if called from a different thread,
// else just append the text directly
if (buildLogConsoleOutputTxtbox.Dispatcher.CheckAccess())
{
// Thread owns the TextBox
buildLogConsoleOutputTxtbox.AppendText(logText + Environment.NewLine);
}
else
{
//Invocation Required
appendLogCallBack appendLog = new appendLogCallBack(buildLogConsoleOutputTxtbox.AppendText);
buildlogScrollEnd buildlogscrl = new buildlogScrollEnd(buildLogConsoleOutputTxtbox.ScrollToEnd);
buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(appendLog, new object[] { logText + Environment.NewLine });
buildLogConsoleOutputTxtbox.Dispatcher.BeginInvoke(buildlogscrl);
}
The Problem with this piece of code is that while I do get the stderr redirected properly to my textbox, This redirection seems to hide the process' stdout output, which I don't want redirected!
If I redirect stdout, I can see it redirected properly, but is it impossible to just redirect stderr and not stdout? I have looked around and googled regarding this topic but all discussions seem to be regarding redirecting stdout ... such as this : How to asynchronously read the standard output stream and standard error stream at once
I would be grateful for any help regarding this!
That is not possible as is - output and error handles are redirected simultaneously. MSDN article STARTUPINFO describes STARTF_USESTDHANDLES
flag.
But there is a good news. Preserving child process output is still possible. You just have to:
So right after process start invoke
[DllImport("Kernel32.dll", SetLastError = true) ]
static extern uint AttachConsole(int pid);
and then use simple Console.WriteLine in your DataReceived
handler.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With