Last active
August 22, 2023 13:28
-
-
Save jonlabelle/867fb6c5ec6514e3fa9389a561b0aa2a to your computer and use it in GitHub Desktop.
Normalize line endings in C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <summary> | |
/// Normalize line endings. | |
/// </summary> | |
/// <param name="lines">Lines to normalize.</param> | |
/// <param name="targetLineEnding">If targetLineEnding is null, Environment.NewLine is used.</param> | |
/// <exception cref="ArgumentOutOfRangeException">Unknown target line ending character(s).</exception> | |
/// <returns>Lines normalized.</returns> | |
/// <remarks> | |
/// https://jonlabelle.com/snippets/view/csharp/normalize-line-endings | |
/// </remarks> | |
public static string NormalizeLineEndings(string lines, string targetLineEnding = null) | |
{ | |
if (string.IsNullOrEmpty(lines)) | |
{ | |
return lines; | |
} | |
targetLineEnding ??= Environment.NewLine; | |
const string unixLineEnding = "\n"; | |
const string windowsLineEnding = "\r\n"; | |
const string macLineEnding = "\r"; | |
if (targetLineEnding != unixLineEnding && targetLineEnding != windowsLineEnding && | |
targetLineEnding != macLineEnding) | |
{ | |
throw new ArgumentOutOfRangeException(nameof(targetLineEnding), | |
"Unknown target line ending character(s)."); | |
} | |
lines = lines | |
.Replace(windowsLineEnding, unixLineEnding) | |
.Replace(macLineEnding, unixLineEnding); | |
if (targetLineEnding != unixLineEnding) | |
{ | |
lines = lines.Replace(unixLineEnding, targetLineEnding); | |
} | |
return lines; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment