Wednesday, May 22, 2013

Replace line breaks in C#

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.

ReplaceLineBreakinC#

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

EnviornmentNewlinelinebreakinC#

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

0 comments:

Post a Comment

Your feedback is very important to me. Please provide your feedback via putting comments.

Search This Blog
Loading...
About Me
My Photo

Full Stack Developer,Blogger,Microsoft Mvp, Mentor, Life long learner, 10+ Years of Experience for JavaScript, web and Microsoft technologies. ASP.NET MVC,Web Forms,C#,AngularJs,Golang
Mvp profile
Subscribe to my blog

Enter your email address:

Follow us on facebook
Blog Archive
Total Pageviews