We have a .NET 5 console application that runs on Windows/Linux/Mac.
Our console application relies on the classic fore color scheme to highlight info/warning/error in console with fore colors gray/yellow/red. However we cannot gather the terminal back color as explained in Console.BackgroundColor documentation:
Unix systems don’t provide any general mechanism to fetch the current console colors. Because of that, BackgroundColor returns (ConsoleColor)-1 until it is set in explicit way (using the setter).
For now we force the console backcolor to be black but this doesn’t render nicely when the terminal back color is white:
If we could guess the terminal back color we could adapt our forecolor to the terminal back color (like black fore color if the terminal back color is white and vice-versa). But from answers to this question How to determine a terminal’s background color? it looks there is no standard way of getting background color that works on Mac and all Linux.
What is the common way to address this?
Advertisement
Answer
Ok we found a solution this way:
- A colored message has white forecolor on a dark enough backcolor, so no matter the user backcolor, colored messages appear highlighted
- Once we modified the
Console.ForegroundColor
andConsole.BackgroundColor
to show a colored message, the astute is to callConsole.ResetColor()
that sets back fore and back colors to their default values
This works no matter the terminal’s default colors.
One point to note is that you shoudn’t call Console.WriteLine(text)
that provokes some back color problems on the remaining line characters. Instead call Console.Write(text)
before Console.ResetColor()
and then line feed is obtained with a call to Console.WriteLine()
.
System.Console.WriteLine("This is an info A"); System.Console.ForegroundColor = ConsoleColor.White; System.Console.BackgroundColor = ConsoleColor.Red; System.Console.Write("This is an error"); System.Console.ResetColor(); System.Console.WriteLine(); System.Console.WriteLine("This is an info B"); System.Console.ForegroundColor = ConsoleColor.White; System.Console.BackgroundColor = ConsoleColor.DarkYellow; System.Console.Write("This is a warning"); System.Console.ResetColor(); System.Console.WriteLine(); System.Console.WriteLine("This is an info C"); System.Console.ForegroundColor = ConsoleColor.White; System.Console.BackgroundColor = ConsoleColor.Green; System.Console.Write("This is a success"); System.Console.ResetColor(); System.Console.WriteLine(); System.Console.WriteLine("This is an info D");