'Does .Net contain a built in Line Endings conversion which checking input format [duplicate]

I'm getting a string from an external native library function which uses "\n" for line separation. I simply want to write this to disk using the appropiate line ending format on the system I'm running my .Net application, which will be usually windows. So "Environment.NewLine" results correctly in "\r\n".

I'm simply write the string to a textfile via

MyString = NativeLib.GetStringEitherLForCRLF();
File.WriteAllText(MyFile, MyString); // will not change LF format

This doesn't changes lineendings, which seems to be intented that way. However, I'm wondering while the same string in C using fwrite in asciimode would probably change the lineendings as I remember.

Since conversion would be an easy task I'm just curios, how the "correct" or best-practice way in .Net should be. Is there a standard function, which would automatically convert the lineendings according to the current environment settings ?


I know how to replace characters in strings, that is not the basic question. The exact question is:

Does there exist a .Net standard library function that will do line ending conversions already depending on OS and Environment settings or which maybe has to be used with a certain parameter to ensure this?

Like e.g.:

File.WriteAllText(MyFile, MyString, Lineencoding.CRLF); // which does not exist

or

File.WriteAllText(MyFile, MyString.ConvertLineendings(Line.CRLF)); // which also does not

But there maybe an option I've missed but it doesn't look like that.
I do not want to write unnecessary boilerplate code to such a trivial task.

The problem is also described in Normalize newlines in C# just to show that I can be more complex than most people think. I'm not completely sure whether the proposed regex solution will work in 100% of all cases.



Solution 1:[1]

If you really get the input as a string (as opposed to a file or something), then create a StringReader over it. On the reader, do .ReadLine() in a loop and write each line to your file (e.g. with a StreamWriter).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Jeppe Stig Nielsen