You can use the String.Replace
method:
string str = sr.ReadToEnd().Replace("\r", "").Replace("\n", "");
However it's not a very good idea if the string is long and you have a long list of illegal characters, because each call to Replace
will create a new instance of String
. A better option would be to filter out the illegal characters using Linq :
char[] illegalChars = new[] { '\r', '\n' }; // add other illegal chars if needed
char[] chars = sr.ReadToEnd().Where(c => !illegalChars.Contains(c)).ToArray();
string str = new String(chars);
However the call to Contains
adds overhead, it is faster to test directly against each illegal character:
char[] chars = sr.ReadToEnd().Where(c => c != '\r' && c != '\n').ToArray();
string str = new String(chars);
And for completeness, here's an even faster version:
StringBuilder sb = new StringBuilder();
foreach(char c in sr.ReadToEnd())
{
if (c != '\r' && c != '\n')
sb.Append(c);
}
string str = sb.ToString();