I try to generate colored console output using ANSI escape codes with the following minimal C# program:
using System;
// test.cs
class foo {
static void
I've created a small plugin (available on NuGet) that allows you to easily wrap your strings in ANSI color codes. Both foreground and background colors are supported.
It works by extending the String
object, and the syntax is very simple:
"colorize me".Pastel("#1E90FF");
After which the string is ready to be printed to the console.
Your program needs to be compiled for /platform:x64
if you use the AnsiCon x64 environment and with /platform:x86
if you use the AnsiCon x86/32 bits version. The exact reason is a mystery...
Originally I thought you need all this:
You need to grab the StandardOutput and let the Console.WriteLine believe you write to a File instead of to a Console and use an ASCII encoding.
This is how it will work:
var stdout = Console.OpenStandardOutput();
var con = new StreamWriter(stdout, Encoding.ASCII);
con.AutoFlush = true;
Console.SetOut(con);
Console.WriteLine("\x1b[36mTEST\x1b[0m");
The .Net Console.WriteLine uses an internal __ConsoleStream
that checks if the Console.Out
is as file handle or a console handle. By default it uses a console handle and therefor writes to the console by calling WriteConsoleW. In the remarks you find:
Although an application can use WriteConsole in ANSI mode to write ANSI characters, consoles do not support ANSI escape sequences. However, some functions provide equivalent functionality. For more information, see SetCursorPos, SetConsoleTextAttribute, and GetConsoleCursorInfo.
To write the bytes directly to the console without WriteConsoleW
interfering a simple filehandle/stream will do which is achieved by calling OpenStandardOutput
. By wrapping that stream in a StreamWriter
so we can set it again with Console.SetOut
we are done. The byte sequences are send to the OutputStream and picked up by AnsiCon.
Do notice that this is only useable with an applicable terminal emulator, like AnsiCon, as shown here: