Is it possible to write to the console in colour in .NET?

C#.Netvb.netColors

C# Problem Overview


Writing a small command line tool, it would be nice to output in different colours. Is this possible?

C# Solutions


Solution 1 - C#

Yes. See this article. Here's an example from there:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");

enter image description here

Solution 2 - C#

class Program
{
    static void Main()
    {
        Console.BackgroundColor = ConsoleColor.Blue;
        Console.ForegroundColor = ConsoleColor.White;
        Console.WriteLine("White on blue.");
        Console.WriteLine("Another line.");
        Console.ResetColor();
    }
}

Taken from here.

Solution 3 - C#

Above comments are both solid responses, however note that they aren't thread safe. If you are writing to the console with multiple threads, changing colors will add a race condition that can create some strange looking output. It is simple to fix though:

public class ConsoleWriter
{
    private static object _MessageLock= new object();

    public void WriteMessage(string message)
    {
        lock (_MessageLock)
        {
            Console.BackgroundColor = ConsoleColor.Red;
            Console.WriteLine(message);
            Console.ResetColor();
        }
    }
}

Solution 4 - C#

I've created a small plugin (available on NuGet) that allows you to add any (if supported by your terminal) color to your console output, without the limitations of the classic solutions.

It works by extending the String object and the syntax is very simple:

"colorize me".Pastel("#1E90FF");

Both foreground and background colors are supported.

enter image description here

Solution 5 - C#

Yes, it's easy and possible. Define first default colors.

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.White;
Console.Clear();

Console.Clear() it's important in order to set new console colors. If you don't make this step you can see combined colors when ask for values with Console.ReadLine().

Then you can change the colors on each print:

Console.BackgroundColor = ConsoleColor.Black;
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Red text over black.");

When finish your program, remember reset console colors on finish:

Console.ResetColor();
Console.Clear();

Now with netcore we have another problem if you want to "preserve" the User experience because terminal have different colors on each Operative System.

I'm making a library that solves this problem with Text Format: colors, alignment and lot more. Feel free to use and contribute.

https://github.com/deinsoftware/colorify/ and also available as NuGet package

Colors for Windows/Linux (Dark):
enter image description here

Colors for MacOS (Light):
enter image description here

Solution 6 - C#

Here is a simple method I wrote for writing console messages with inline color changes. It only supports one color, but it fits my needs.

// usage: WriteColor("This is my [message] with inline [color] changes.", ConsoleColor.Yellow);
static void WriteColor(string message, ConsoleColor color)
{
    var pieces = Regex.Split(message, @"(\[[^\]]*\])");

    for(int i=0;i<pieces.Length;i++)
    {
        string piece = pieces[i];
        
        if (piece.StartsWith("[") && piece.EndsWith("]"))
        {
            Console.ForegroundColor = color;
            piece = piece.Substring(1,piece.Length-2);          
        }
        
        Console.Write(piece);
        Console.ResetColor();
    }
    
    Console.WriteLine();
}

image of a console message with inline color changes

Solution 7 - C#

Just to add to the answers above that all use Console.WriteLine: to change colour on the same line of text, write for example:

Console.Write("This test ");
Console.BackgroundColor = bTestSuccess ? ConsoleColor.DarkGreen : ConsoleColor.Red;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine((bTestSuccess ? "PASSED" : "FAILED"));
Console.ResetColor();

Solution 8 - C#

Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour

Solution 9 - C#

A sample method to color multiple words at the same time.

private static void WriteColor(string str, params (string substring, ConsoleColor color)[] colors)
{
	var words = Regex.Split(str, @"( )");

	foreach (var word in words)
	{
		(string substring, ConsoleColor color) cl = colors.FirstOrDefault(x => x.substring.Equals("{" + word + "}"));
		if (cl.substring != null)
		{
			Console.ForegroundColor = cl.color;
			Console.Write(cl.substring.Substring(1, cl.substring.Length - 2));
			Console.ResetColor();
		}
		else
		{
			Console.Write(word);
		}
	}
}

Usage:

WriteColor("This is my message with new color with red", ("{message}", ConsoleColor.Red), ("{with}", ConsoleColor.Blue));

Output:

enter image description here

Solution 10 - C#

I developed a small fun class library named cConsole for colored console outputs.
Example usage:

const string tom = "Tom";
const string jerry = "Jerry";
CConsole.WriteLine($"Hello {tom:red} and {jerry:green}");

It uses some functionalities of C# FormattableString, IFormatProvider and ICustomFormatter interfaces for setting foreground and background colors of text slices.
You can see cConsole source codes here

Solution 11 - C#

I did want to just adjust the text color when I want to use Console.WriteLine(); So I had to write

Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine("my message");
Console.ResetColor();

every time that I wanted to write something

So I invented my WriteLine() method and kept using it in Program class instead of Console.WriteLine()

public static void WriteLine(string buffer, ConsoleColor foreground = ConsoleColor.DarkGreen, ConsoleColor backgroundColor = ConsoleColor.Black)
{
   Console.ForegroundColor = foreground;
   Console.BackgroundColor = backgroundColor;
   Console.WriteLine(buffer);
   Console.ResetColor();
}

and to make it even easier I also wrote a Readline() method like this:

public static string ReadLine()
{
   var line = Console.ReadLine();
   return line ?? string.Empty;
}

so now here is what we have to do to write or read something in the console:

static void Main(string[] args) {
   WriteLine("hello this is a colored text");
   var answer = Readline();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNibblyPigView Question on Stackoverflow
Solution 1 - C#Mark ByersView Answer on Stackoverflow
Solution 2 - C#Darin DimitrovView Answer on Stackoverflow
Solution 3 - C#Roger HillView Answer on Stackoverflow
Solution 4 - C#silkfireView Answer on Stackoverflow
Solution 5 - C#equimanView Answer on Stackoverflow
Solution 6 - C#Walter StaboszView Answer on Stackoverflow
Solution 7 - C#DaapView Answer on Stackoverflow
Solution 8 - C#Chamila MaddumageView Answer on Stackoverflow
Solution 9 - C#RansView Answer on Stackoverflow
Solution 10 - C#Ramin RahimzadaView Answer on Stackoverflow
Solution 11 - C#SReza SView Answer on Stackoverflow