Indent multiple lines of text

Since you are indenting all the lines, how about doing something like:

var result = indent + textToIndent.Replace("\n", "\n" + indent);

Which should cover both Windows \r\n and Unix \n end of lines.


The following solution may seem long-winded compared to other solutions posted here; but it has a few distinct advantages:

  • It will preserve line separators / terminators exactly as they are in the input string.
  • It will not append superfluous indentation characters at the end of the string.
  • It might run faster, as it uses only very primitive operations (character comparisons and copying; no substring searches, nor regular expressions). (But that's just my expectation; I haven't actually measured.)
static string Indent(this string str, int count = 1, char indentChar = ' ')
{
    var indented = new StringBuilder();
    var i = 0;
    while (i < str.Length)
    {
        indented.Append(indentChar, count);
        var j = str.IndexOf('\n', i + 1);
        if (j > i)
        {
            indented.Append(str, i, j - i + 1);
            i = j + 1;
        }
        else
        {
            break;
        }
    }
    indented.Append(str, i, str.Length - i);
    return indented.ToString();
}

Just replace your newline with newline + indent:

var indentAmount = 4;
var indent = new string(' ', indentAmount);
textToIndent = indent + textToIndent.Replace(Environment.NewLine, Environment.NewLine + indent);