C# tip: using ANSI colors in console applications
Posted: (EET/GMT+2)
Modern Windows consoles support ANSI escape sequences (Microsoft calls these Virtual Terminal Sequences), which makes it easy to print colored text in C# console applications.
In older Windows versions this required special configuration using the Win32 API function SetConsoleMode() and the ENABLE_VIRTUAL_TERMINAL_INPUT (code 0x0200) option, but current Windows Terminal and modern Windows console hosts support ANSI sequences out of the box.
Example: printing colored text.
Console.WriteLine("\x1b[31mThis text is red\x1b[0m");
Console.WriteLine("\x1b[32mThis text is green\x1b[0m");
Console.WriteLine("\x1b[33mThis text is yellow\x1b[0m");
The sequence begins with \u001b (the ESC character), followed by formatting
codes.
Common examples:
31= red32= green33= yellow34= blue0= reset formatting
Example with variables:
string red = "\x1b[31m";
string reset = "\x1b[0m";
Console.WriteLine($"{red}Error occurred{reset}");
This approach works well for CLI tools, build scripts, and utilities where colored output improves readability.
.NET also supports colors through Console.ForegroundColor, but ANSI sequences
are convenient when you want to embed formatting directly into strings.