Make c# 11 raw string literals' newline use \r\n instead of \n

993 Views Asked by At

New C# 11 feature "raw string literals" seems to be using \n to break the line:

const string text = """
    "header1";"header2"
    "value1";"value2"
    """;

This will produce "header1";"header2"\n"value1";"value2"\n

How can I make it produce "header1";"header2"\r\n"value1";"value2"\r\n?

1

There are 1 best solutions below

0
Alex Siepman On

I had problemen with string literals and unit tests. On my PC Environment.NewLine was different from the buildserver. So test results where different for:

$"a{Environment.NewLine}b" 

and

"""
a
b
"""

So I changed the second to:

"""
a
b
""".UseEnvironmentNewLine();

using these extensions methods:

public static string UseUnixNewLine(this string value) => value.UseSpecificNewLine("\n");
public static string UseWindowsNewLine(this string value) => value.UseSpecificNewLine("\r\n");
public static string UseEnvironmentNewLine(this string value) => value.UseSpecificNewLine(Environment.NewLine);
public static string UseSpecificNewLine(this string value, string specificNewline) => Regex.Replace(value, @"(\r\n|\r|\n)", specificNewline);

If you want a \r\n as line end. Just do this:

string text = """
    "header1";"header2"
    "value1";"value2"
    """.UseWindowsNewLine();