Tuesday, November 27, 2007

Displaying different colored text to the console (just like MSBuild)

[This was originally posted at http://timstall.dotnetdevelopersjournal.com/displaying_different_colored_text_to_the_console_just_like_.htm]

I really like how MSBuild displays different colored text to the console - red for errors, yellow for warnings, green for success, etc... It's just a nice perk.

You can easily do this too using Console.ForegroundColor. For example, the following code has a master method "_ConsoleWrite" that takes the text and a ConsoleColor. It then keeps track of the original color, writes the text in the new color, and restores the original. It's simple, but adds a nice touch to a console app.


    private static void _ConsoleWrite(string strText, ConsoleColor cWrite)
    {
      ConsoleColor cOriginal = Console.ForegroundColor;

      Console.ForegroundColor = cWrite;
      Console.WriteLine(strText);

      Console.ForegroundColor = cOriginal;
    }

 

    public static void ConsoleWriteNormal(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Gray);
    }

    public static void ConsoleWriteError(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Red);
    }

    public static void ConsoleWriteWarning(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Yellow);
    }

    public static void ConsoleWriteSuccess(string strText)
    {
      _ConsoleWrite(strText, ConsoleColor.Green);
    }

No comments:

Post a Comment