简体   繁体   中英

c# Console.WriteLine() with color text is massing the output

I am trying to show a warning to the user by the following code. But it is massing the output text.

Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Red;
Console.WriteLine($"The selected row {selection} is not found in the database.");
Console.ResetColor();
Console.ReadLine();
Environment.Exit(0);

The display looks as follows:- 在此输入图像描述

I only want to make coloring of the text "The selected row is not found in the database." . Nothing extra. Otherwise it looks ugly. How to do it?

The problem is that the carriage return and new line draws the background color for these lines. Simply use Console.Write() instead of Console.WriteLine() :

Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.Red;
// only write without new line
Console.Write($"The selected row {selection} is not found in the database.");
Console.ResetColor();
Console.WriteLine(); // if necessary
Console.ReadLine();
Environment.Exit(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM