3

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?

6
  • 8
    Raw literals don't use \n. They use whatever you typed. Your editor saved the source code with \n instead of \r\n. Why do you want this though? What are you trying to do? You may not need \r\n at all. Commented Dec 8, 2022 at 12:50
  • If you want to generate a CSV file a better solution would be to use a library like CsvHelper and specify the culture, field, line separators you want. Quoting values isn't as easy as adding " everywhere. Most applications will work just fine with ``n though. Excel certainly does. Commented Dec 8, 2022 at 12:52
  • 1
    Another option would be to use a StreamWriter or StringBuilder and explicitly emit the separators you want. Hard-coding EU-style separators will cause problems on every machine using the US style. Commented Dec 8, 2022 at 12:53
  • @PanagiotisKanavos it's part of a unit test for verifying a generated csv. I need the string as a constant. I was refactoring it using the new feature and found out that I'm unable to specify the correct newline chars. Commented Dec 8, 2022 at 12:57
  • 1
    Save the file to disk then and include it as content. Otherwise you'll find your editor all the time as it tries to normalize line endings. You can specify the "correct" newline. Your editor will change it though Commented Dec 8, 2022 at 13:10

1 Answer 1

7

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(); 
Sign up to request clarification or add additional context in comments.

2 Comments

...or you add a .gitignore that ensures all environments (Windows, Linux, macOS) use the same type of newlines.
I think that you meant .gitattributes :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.