Search code examples
c#console

Indent multiline text in console


Is there clean way to indent multiline text in the console?

For example, when you write the code bellow, only first line appears indented.

Console.WriteLine($"  {ex.Message}");

Solution

  • There's no built-in way to do this, but one way is to use Regex.Replace to add indentation at the beginning on each line. With RegexOptions.Multiline a ^ matches the beginning of each line:

    // ex.Message = "This is a sting with\nmultiple lines of text\r\nwith different line endings";
    var indented = Regex.Replace(ex.Message, "^", "  ", RegexOptions.Multiline);
    Console.WriteLine(indented);
    
      This is a sting with
      multiple lines of text
      with different line endings
    

    https://dotnetfiddle.net/ArfVeH