Skip to content

Instantly share code, notes, and snippets.

@jonlabelle
Last active August 22, 2023 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jonlabelle/867fb6c5ec6514e3fa9389a561b0aa2a to your computer and use it in GitHub Desktop.
Save jonlabelle/867fb6c5ec6514e3fa9389a561b0aa2a to your computer and use it in GitHub Desktop.
Normalize line endings in C#.
/// <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