Last post Dec 28, 2006 02:24 PM by ElGreco
Dec 27, 2006 02:29 PM|ElGreco|LINK
I have been trying to remove CR LF characters from a text(csv) file. My code looks something like this (see below), but the '\r' and '\n' characters do not seem to be replaced. can anyone see anything obviously wrong?
Is there a better way?
val = stream.ReadToEnd();
Dec 27, 2006 04:29 PM|ecbruck|LINK
string val = stream.ReadToEnd().Replace('\r', '\0').Replace('\n', '\0');
Dec 27, 2006 06:21 PM|pickyh3d|LINK
Replacing the newlines with the null terminator is probably not what you want. You probably meant to replace them with nothing (String.Empty, or ""): Note I am not using single quotes (characters), rather double quotes for a string.
val = stream.ReadToEnd().Replace("\r", "").Replace("\n", "");
Dec 27, 2006 07:29 PM|pickyh3d|LINK
I also just noticed that you are not setting val equal to the value that you're changing it to: val.Replace('\r', '\0'); returns a new string with the specified values swapped. It does not change the existing variable, val's, value. You would need to do
val = val.Replace('\r', '\0'); and val = val.Replace('\n', '\0'); if you did not want to do it all on one line similar to ecbruck's code.
The reason both of our examples would work (for what we wanted them to do) is because we are changing the returned string and saving the final result to val.
Now, if you really wanted to replace \r and \n with the null terminator (\0, or character 0) instead of removing the characters, then use ecbruck's code. If you wanted to remove the characters, then you should use my code.
Dec 28, 2006 02:24 PM|ElGreco|LINK
Thanks very much for your help. It seems the reason my code failed was because I did not update the existing variable val's value.
The interesting result of this is that whilst it removes the offending CRLF characters in the text file, It also removes the end of line characters (which one would expect) except that in the source file my text editor (SCITE) only shows the offending CRLF
scattered throught the file, and it does not show the end of line characters. Odd.