Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - ANSI-Coloring Console Output with .NET

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[36mTESTx1b[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[36mTESTx1b[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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...