I want to make sure that _content does not end with a NewLine character:
_content = sb.ToString().Trim(new char[] { Environment.NewLine });
The following works for me.
sb.ToString().TrimEnd( '\r', '\n' );
or
sb.ToString().TrimEnd( Environment.NewLine.ToCharArray());
I had to remove the new lines all over the text. So I used:
while (text.Contains(Environment.NewLine))
{
text = text.Substring(0, text.Length - Environment.NewLine.Length);
}
How about just:
string text = sb.ToString().TrimEnd(null)
That will pull all whitespace characters from the end of the string -- only a problem if you wanted to preserve non-newline whitespace.
What about
_content = sb.ToString().Trim(Environment.NewLine.ToCharArray());
.Trim()
removes \r\n
for me (using .NET 4.0).
Somewhat of a non-answer, but the easiest way to trim a newline off of a string is to not have the newline on the string in the first place, by making sure it is is never seen by your own code. That is, by using native functions which remove the newline. Many stream and file/io methods will not include the newline if you ask for output line by line, though it may be necessary to wrap something in a System.IO.BufferedStream
.
Things like System.IO.File.ReadAllLines
can be used in place of System.IO.File.ReadAllText
most of the time, and ReadLine
can be used instead of Read
once you are working with the right type of stream (e.g. BufferedStream
).