Skip to content

Instantly share code, notes, and snippets.

@pavelhodek
Forked from jonlabelle/NormalizeLineEndings.cs
Created August 22, 2023 13:28
Show Gist options
  • Select an option

  • Save pavelhodek/8d1e553685c4696e59c4bb25dea944e7 to your computer and use it in GitHub Desktop.

Select an option

Save pavelhodek/8d1e553685c4696e59c4bb25dea944e7 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