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.

Revisions

  1. @jonlabelle jonlabelle revised this gist Nov 20, 2020. No changes.
  2. @jonlabelle jonlabelle created this gist Nov 20, 2020.
    41 changes: 41 additions & 0 deletions NormalizeLineEndings.cs
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,41 @@
    /// <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;
    }