Skip to main content

C# extension method to convert line endings in the string to the current Environment.NewLine.

/// <summary>
/// Converts line endings in the string to <see cref="Environment.NewLine"/>.
/// </summary>
public static string NormalizeLineEndings(this string str)
{
    return str.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", Environment.NewLine);
}

// or

/// <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>
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;
}