Search code examples
c#.net-coretabsstreamwriter.net-core-2.0

Ident Tabs for Multiple New Line String Variable in Net Core


How do I ident a set of lines when writing to a file, with a tabs? I need to go through each line in the variable and create 8 spaces or two tabs for each line, when writing to the new file.

If the string was one line, it would be easy, with " " + test, however this has multiple lines.

public static string testLine=
        "Line1" + Environment.NewLine +
        "Line2" + Environment.NewLine +
        "Line3" + Environment.NewLine +
        "Line4" + Environment.NewLine +

 using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath, true))
 {
        file.WriteLine(testLine);

String is composed of new line, line breaks enters, etc .

Is there any Microsoft Ident function library to support this? Needs to handle multiple string variables in the future.


Solution

  • All you need to do is prefix the string with whitespace or a tab and replace all occurences of newlines with a newline and a suitable whitespace:

    testLine = "    " + testLine.Replace( Environment.NewLine, Environment.NewLine + "    " );
    

    You can explicitly handle an empty string to avoid indenting nothing:

    testLine = String.IsNullOrEmpty(testLine) ? testLine : "    " + testLine.Replace( Environment.NewLine, Environment.NewLine + "    " );
    

    Substitute "\t" for " " to insert a tab character.