✅ Why does Console.WindowWidth produce Invalid Handle when the app is invoked from Process?

I have two console application projects: HelloWorld and Invoker. HelloWorld
try
{
Console.Out.WriteLine(new string('=', Console.WindowWidth));
}
catch (Exception e)
{
Console.Error.WriteLine($"HelloWorld's error: {e.Message}");
}
try
{
Console.Out.WriteLine(new string('=', Console.WindowWidth));
}
catch (Exception e)
{
Console.Error.WriteLine($"HelloWorld's error: {e.Message}");
}
It works fine when executed directly. Invoker
ProcessStartInfo info = new()
{
FileName = "helloworld.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
};

using var process = new Process { StartInfo = info };
process.Start();

Task? outputTask = null;

if (!info.UseShellExecute && info.RedirectStandardError)
{
var errorWriter = process.StandardError;
Console.WriteLine($"Error: {errorWriter.ReadToEnd()}");
}

if(outputTask is not null) await outputTask;
await process.WaitForExitAsync();
ProcessStartInfo info = new()
{
FileName = "helloworld.exe",
RedirectStandardOutput = true,
RedirectStandardError = true,
};

using var process = new Process { StartInfo = info };
process.Start();

Task? outputTask = null;

if (!info.UseShellExecute && info.RedirectStandardError)
{
var errorWriter = process.StandardError;
Console.WriteLine($"Error: {errorWriter.ReadToEnd()}");
}

if(outputTask is not null) await outputTask;
await process.WaitForExitAsync();
It produces
Error: HelloWord's error: The handle is invalid.
What is wrong?
1 Reply
canton7
canton74mo ago
From the remarks (https://learn.microsoft.com/en-us/dotnet/api/system.console.windowwidth?view=net-8.0#remarks):
Attempting to set the value of the WindowWidth property when output is redirected throws either an ArgumentOutOfRangeException or an IOException exception. To prevent an exception, you can set the value of this property only if the IsOutputRedirected property returns false.
And intuitively, there's no console when the output is being read directly by something else, so there's nothing to get the width of