JohnJackson
JohnJackson

Reputation: 87

\r\n in C# not replaced

I have this string read from a table in sql:

 Yderligere tillidshverv:
Medlem af bestyrelsen for Dansk XXSW, region Århus.
Andre aktiviteter:
Opfinder af 123 trapper.    

What I want to do is replace occurences of \r\n with just a single \n. However it is not working. The problem is that notepad++ still shows CRLF. It should only show LF. What am I missing? Here is my code:

string x = returnValue.Replace("\r\n", "\n");

Upvotes: 1

Views: 822

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

When you paste a string from a Windows clipboard into Notepad++, the linebreaks get converted to the line ending style set for the current document (see the bottom of the screen).

enter image description here

If you right click and select UNIX, you will be able to paste the string with \n only. This will also change all line endings to LF.

If you do not want to change all line endings in the document to LF, you can use EDIT > Paste Special -> Paste Binary Content

However, from C#, you can just write the variable content into a text file:

var s = "I know\r\nit should\r\n";
var b = s.Replace("\r\n", "\n");
using (var sw = new StreamWriter(@"PATH_TO_FILE", false, Encoding.UTF8))
{
    sw.Write(b);
}

And enjoy \n linebreaks.

Upvotes: 3

buckley
buckley

Reputation: 14071

Using the Regex class will work. I used linqpad to quickly test code which has the Dump() extension method

Regex.Replace("test\r\ntest","\r\n","\n").Select(x => x).Dump();

Update : A regular replace also works BTW. You state that it doesn't?

"test\r\ntest".Replace("\r\n","\n").Select(x => x).Dump();

Upvotes: -1

Related Questions