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.
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.
And now once you run this. It will work in all the environment
That’s it. Hope you like it. Stay tuned for more..
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..
0 comments:
Post a Comment
Your feedback is very important to me. Please provide your feedback via putting comments.