I wish to create a string that contains a list of stuff with one item on each line, but the following code doesn’t maintain the new lines:
foreach (DateTime date in dates)
{
datelist += date.ToString("yyyy/MM/dd") + Environment.NewLine;
}
string mystring = String.Format(@"Hey there here is a list of dates
Dates:
{0}",
datelist);
Output:
Hey there here is a list of dates
Dates:
2012/03/04 2012/03/05 2012/03/06
Desired output:
Hey there here is a list of dates
Dates:
2012/03/04
2012/03/05
2012/03/06
I tried variations, such as two Environment.NewLines, escapes like \r\n, starting the string with @, and so on, and I could not get my desired output.
I was ultimately able to solve my problem by putting a symbol into the string where I want linebreaks, and then use string.Replace to change the symbol to Environment.NewLine:
foreach (DateTime date in dates)
{
datelist += date.ToString("yyyy/MM/dd") + "<br />";
}
string mystring = String.Format(@"Hey there here is a list of dates
Dates:
{0}",
datelist.Replace(Environment.NewLine, "<br />"));
Like I said, this works, but I wish to know why good old concatenation doesn’t work when inserting a string with lines into another string, as well as what the standard/common solution to my question would be.
If you render HTML output, you shouldn’t use
Environment.NewLine– use<br />instead. Multiple consecutive whitespace (including\rand\n) may be aggregated by the browser into a single whitespace. (Based on my experience, the actual behavior is somewhat browser dependent but I didn’t actually research into this.)If somewhere within the string you need multiple blank lines, use multiple
<br />-s, of course.