I have a console application that is developed using .Net 6.0. Following code works when I run this application directly from the console.
string l_ErrMsg = "Error !";
Console.Error.WriteLine(l_ErrMsg); // works
Console.WriteLine(l_ErrMsg); // works
But when I invoke the same console application from another console application, 'Console.Error.WriteLine(l_ErrMsg)' does not work.
string l_ErrMsg = "Error !";
Console.Error.WriteLine(l_ErrMsg); // Does not work
Console.WriteLine(l_ErrMsg); // works
Both are console applications and developed using .Net 6.0. Following is the code to invoke the applicaiton:
using (var process = new System.Diagnostics.Process())
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = "\\Some\\Path";
process.StartInfo.FileName = "MyApp.exe";
string l_errorOut = null;
process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{ l_errorOut += e.Data; });
string l_CmdLine = string.Format("--Arg1={0}", argument1);
process.StartInfo.Arguments = l_CmdLine;
lbProcessStarted = process.Start();
}
Based on what @Dai Suggested. Here is the final code:
using (var process = new System.Diagnostics.Process())
{
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.WorkingDirectory = Path.Combine(BinaryPath, "..\\SomePath");
process.StartInfo.FileName = "MyApp.exe";
process.ErrorDataReceived += new DataReceivedEventHandler((sender, e) =>
{
// This will write to console
WriteLine(e.Data);
});
string l_CmdLine = string.Format("--Arg1={0}", argument1);
process.StartInfo.Arguments = l_CmdLine;
lbProcessStarted = process.Start();
process.BeginErrorReadLine();
process.WaitForExit();
if (process != null)
{
process.Close();
}
}