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.
Replacing
@"\n"with@"\n"will turn@"\n\r"(old mac line endings) into@"\n\n\r". You would be better off using aRegexwith@"[\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 useString.Spliton both'\r'and'\n'withStringSplitOptions.RemoveEmptyEntriesthen useString.Joinpassing@"\r\n"as the join separator. That's because I'm usually doing things with each line anyways.