What is the easiest way in C# to trim a newline off of a string?

The following works for me.

sb.ToString().TrimEnd( '\r', '\n' );

or

sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());

.Trim() removes \r\n for me (using .NET 4.0).


How about:

public static string TrimNewLines(string text)
{
    while (text.EndsWith(Environment.NewLine))
    {
        text = text.Substring(0, text.Length - Environment.NewLine.Length);
    }
    return text;
}

It's somewhat inefficient if there are multiple newlines, but it'll work.

Alternatively, if you don't mind it trimming (say) "\r\r\r\r" or "\n\n\n\n" rather than just "\r\n\r\n\r\n":

// No need to create a new array each time
private static readonly char[] NewLineChars = Environment.NewLine.ToCharArray();

public static string TrimNewLines(string text)
{
    return text.TrimEnd(NewLineChars);
}

Use the Framework. The ReadLine() method has the following to say:

A line is defined as a sequence of characters followed by a line feed ("\n"), a carriage return ("\r") or a carriage return immediately followed by a line feed ("\r\n"). The string that is returned does not contain the terminating carriage return or line feed.

So the following will do the trick

_content = new StringReader(sb.ToString()).ReadLine();