Display \r\n to text file

A

Amy L.

I have a scenario where I am writing a string to a text file. Very often
the string may contain a \r\n in it. When I write this info to the text
file it will interpret the \r\n and insert the new line as one would think
it would.

How can I make it so that the string abcdef\r\nghijkl displays just like
that instead of
abcdef
ghijkl

I tried using the "@" before the string, but that did not work.

Any thoughts?
Amy
 
B

Bob Grommes

Amy,

If you want to put a constant into code that will display literally I
believe that double backslashes will cancel the escape, e.g.:

"abcdef\\r\\nghijkl" will display or write to a stream as:
"abcdef\r\n\ghijkl".

If you simply want to transform something with embedded newline sequences,
you could just do:

DoWhateverWith(someStringWithNewLines.Replace("\r\n","\\r\\n"));

--Bob
 
J

Jon Skeet [C# MVP]

Amy L. said:
I have a scenario where I am writing a string to a text file. Very often
the string may contain a \r\n in it. When I write this info to the text
file it will interpret the \r\n and insert the new line as one would think
it would.

How can I make it so that the string abcdef\r\nghijkl displays just like
that instead of
abcdef
ghijkl

I tried using the "@" before the string, but that did not work.

It should have done (depending on exactly what you mean by "before the
string" - could you post a short but complete program which
demonstrates the problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,

The literal string should be displayed correctly.


Anyway, I think this should work

stringvar.Replace( Environment.NewLine , "\\r\\n" );

Cheers,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top