0

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?

Bizhan
  • 16,157
  • 9
  • 63
  • 101
  • 7
    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. – Panagiotis Kanavos Dec 08 '22 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. – Panagiotis Kanavos Dec 08 '22 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. – Panagiotis Kanavos Dec 08 '22 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. – Bizhan Dec 08 '22 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 – Panagiotis Kanavos Dec 08 '22 at 13:10
  • Thanks. I think I'll try a partial class with CRLF line ending and force it to git as described here: https://stackoverflow.com/questions/10357436/how-to-make-git-not-change-line-endings-for-one-particular-file – Bizhan Dec 08 '22 at 13:49

0 Answers0