0

I am working on a C# console project in Visual Studio, and I want to change the color of a portion of a StringBuilder object. I can't write that part of the code to the console immediately with a WriteLine because it's part of a larger paragraph. Therefore, the solution presented in Is it possible to write to the console in colour in .NET? (using WriteLine statements between ConsoleColor.Cyan statements) is not applicable.

This is my current method:

internal void ShowItems(StringBuilder builder, Player player)
{
    foreach (Item item in Program.items.Values)
    {
        if (item.CurrentLocation == player.CurrentLocation.Name && item.CurrentLocation == item.InitialLocation)
        {
            builder.Append(item.InitialText);
        }
        else if (item.CurrentLocation == player.CurrentLocation.Name && item.CurrentLocation != item.InitialLocation)
        {
            builder.Append($" You see the {item.DisplayName.ToUpper()} here.");
        }
    }
}  

I want part of the item.InitialText to appear in another color, say magenta. This color is different than the rest of the text. I can split item.InitialText, into the strings I want, but how do I make one of those strings a different color?

I have looked in several resources, but they all seem to be for rich text boxes or other graphical interfaces, not console output.

Rob
  • 26,989
  • 16
  • 82
  • 98
Super Jade
  • 5,609
  • 7
  • 39
  • 61
  • https://stackoverflow.com/questions/2743260/is-it-possible-to-write-to-the-console-in-colour-in-net – Blorgbeard Oct 20 '17 at 21:36
  • 1
    A string doesn't have a colour (and neither does a SringBuilder), but you can print in colour at the time when you actually write to the console. You'll have to rig your own method of remembering which colour to print each stirng in. Maybe a custom class that contains a string and a `ConsoleColor`. – Blorgbeard Oct 20 '17 at 21:40
  • @Blorgbeard I edited my original post. The reference to the other stackoverflow post does not apply. – Super Jade Oct 20 '17 at 22:05
  • It doesn't look edited to me.. – Blorgbeard Oct 20 '17 at 22:06
  • @Blorgbeard Better? – Super Jade Oct 20 '17 at 22:23
  • Please don't include answers in your question. Even if the question is closed. In any case, it looks like your solution is using the same idea as the closed duplicate (writing a colour to the *console*, not into a string builder (which people have already mentioned is impossible)). This question should stay as a duplicate, as it's really asking how to print colour to the console. – Rob Nov 03 '17 at 01:00

0 Answers0