User Id :    Password :      New Member   Forgot Password  
 
Replace line breaks in C#
Description In recent days I was working on a project want to replace \r\n to a new character but it was giving very strange behaviour. It was not replacing proper.   No. of Views     1320
  Rating     0
Author Jalpesh Vadgama   Posted On     30 May 2013
Tags C#,C# 4.0    

Sample Code   Download Code

 

In recent days I was working on a project want to replace \r\n to a new character but it was giving very strange behaviour. It was not replacing proper. Let’s create that scenario. I have written following code.

 
 

using System;
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sample = @"This is string for replacing new
                                 line \r\n This may not work";
            Response.Write(sample.Replace(@"\r\n",@"<br />"));
        }
    }
}

 

If you see the above code looks like it should work fine. But when you run this in browser in some environment it working fine and in some environment it was not working fine. Just like below



So after getting in that situation I dig into it and found that and I found that various operating system environment has various character for new line characters and that’s the reason that it was working sometimes and sometime does not. So it’s always better to use ‘System.Environment.NewLine’ instead of using strings like \r\n.


You can find more information about new line character here.

http://en.wikipedia.org/wiki/Newline

So after putting above solution my code looks like following.


 


using System;
 
namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string sample = @"This is string for replacing new
                         line \r\n This may not work";
            Response.Write(sample.Replace(Environment.NewLine,
                            @"<br />"));
        }
    }
}



And now once you run this. It will work in all the environment




That’s it. Hope you like it. Stay tuned for more..

 

About Author

About Author I am jalpesh vadgama an Microsoft MVP for Visual C# and BrainBench Certified ASP.NET Developer having more then 5 years of experience in .NET Technology.Please feel free to contact me for any queries via posting comments on my blog I will try to reply as early as possible. Please also visit my blog at http://jalpesh.blogspot.com/ Jalpesh Vadgama
No Photo
 
Country India
Company N/A
Home Page http://jalpesh.blogspot.com/

Rate this article

Rating options from poor, fair, good, very good to excelent.  
 

Comments

   
Write your comment here.
Comment
Verification Code