1

I developed an application in .NET 6 that joins .txt files. When it is generated in the Windows environment, CRLF is displayed at the end of each line, but in the linux environment it only displays LF. What would be the solution to generate with CRLF characters?

I already tried the replace below and it didn't work:

var targetLineEnding = Environment.NewLine;
var unixLineEnding = "\\n";
var windowsLineEnding = "\\r\\n";

if (targetLineEnding != windowsLineEnding)
    line = line.Replace(unixLineEnding, windowsLineEnding);

I need the CR+LF characters to be generated regardless of the environment in which the application is running.

Panagiotis Kanavos
  • 120,703
  • 13
  • 188
  • 236
Junior
  • 11
  • 1
  • `\r\n` works. If the *replacement* doesn't work it's because that pair of characters doesn't exist in the string. Where did `line` come from? If you used any kind of StreamReader, either directly or through `File.ReadLines`, there won't be any newline characters. – Panagiotis Kanavos Jul 03 '23 at 14:45
  • 1
    It sounds like the real question is how to *use* CR+LF, not replace anything. Even on Windows though, many applications work just fine with just LF. What are you trying to do? Generate a CSV file perhaps? – Panagiotis Kanavos Jul 03 '23 at 14:49
  • 1
    You're currently performing a replacement of "backslash followed by n" with "backslash followed by r, then backslash followed by n". Those strings don't have any carriage return or line feed characters. *Why* are you escaping the backslashes? – Jon Skeet Jul 03 '23 at 14:55
  • I am writing a new file from WriteLine (StreamWriter). In debug mode these characters do not appear in the string. I can only identify through Notepad++ (View->Show Symbol->Show End Of Line) – Junior Jul 03 '23 at 15:12
  • I am not sure what you have been looking at (I guess the string to be written itself) but as can be seen [here](https://source.dot.net/#System.Private.CoreLib/src/libraries/System.Private.CoreLib/src/System/IO/StreamWriter.cs,54025e8b7ea2ef53,references) `WriteLine` simply calls `WriteSpan` which appends the platform dependent characters. So you should get the same characters that are presented by you in [`Environment.NewLine`](https://learn.microsoft.com/en-us/dotnet/api/system.environment.newline?view=net-7.0). In addition (as Jon already pointed out), you are replacing `\\n` not `\n`. – Markus Safar Jul 03 '23 at 15:55

1 Answers1

0

Replacing @"\n" with @"\n" will turn @"\n\r" (old mac line endings) into @"\n\n\r". You would be better off using a Regex with @"[\n\r]+$" this will match one or more of both characters until end of line. Another alternative I use when parsing files is to read in the whole file in and use String.Split on both '\r' and '\n' with StringSplitOptions.RemoveEmptyEntries then use String.Join passing @"\r\n" as the join separator. That's because I'm usually doing things with each line anyways.

Charles Lambert
  • 5,042
  • 26
  • 47