How to generate CRLF characters in application hosted on Linux server C#

80 views Asked by At

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.

1

There are 1 answers

0
Charles Lambert On

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.