ANSI-Coloring Console Output with .NET

Tomalak picture Tomalak · Dec 3, 2015 · Viewed 8.2k times · Source

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 Main(string[] args) {
        Console.WriteLine("\x1b[36mTEST\x1b[0m");
    }
}

I am running Ansicon v1.66 on Windows 7 x64 with csc.exe (Microsoft (R) Visual C# Compiler version 4.6.0081.0).

Colored output works fine in this configuration; Ansicon itself is working flawlessly.

To cross-check I use a node.js one-liner that is 100% equivalent to the C# program:

// test.js
console.log("\x1b[36mTEST\x1b[0m");

And, even more basic, a hand-crafted text file:

text file hex editor screenshot

Both of which which correctly do the expected thing: Print a teal-colored string "TEST":

enter image description here

Only the test.exe I built with csc prints something else. Why?

Answer

silkfire picture silkfire · Dec 5, 2018

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.

enter image description here

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.