Why does StringBuilder.AppendLine not add a new line with some strings?

无人久伴 提交于 2019-12-01 14:55:47

Instead of

sbUser.AppendLine();

Try using

sbUser.Append(Environment.NewLine);

No idea why this works...

cjmurph

I know the question is old and has been marked as answered, but I thought I'd add this here in case anyone else comes across this as it's the first hit on Google for StringBuilder.AppendLine() not working.

I had the same problem and it turned out to be an Outlook issue. Outlook re-formats text based emails by removing extra line breaks. You can click "We removed extra line breaks in this message -> Restore line breaks" in the header of the individual email, or change the setting that does this nasty little trick "Options->Mail->Message Format->Remove extra line breaks in plain text messages"

The workaround (since you can't control the settings on every potential email target) I found here Newsletter Formatting And The Remove Extra Line Breaks Issue. Basically, if you add two white space characters to the beginning of each line, Outlook won't reformat the email.

Here's an extension method to help (method name is a bit verbose so change to your liking :))

namespace System.Text
{
    public static class StringBuilderExtensions
    {
        public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb, string value)
        {
            sb.AppendFormat("{0}{1}{2}", "  ", value, Environment.NewLine);
        }

        public static void AppendLineWithTwoWhiteSpacePrefix(this StringBuilder sb)
        {
            sb.AppendFormat("{0}{1}", "  ", Environment.NewLine);
        }
    }
}

use Environment.NewLine

sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone@somewhere.com");
sbUser.AppendLine(Environment.NewLine);
sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle); 
sbUser.AppendLine("Date of event : " + thisEvent.EventStartDate.ToString("dd MMM yyyy"));
sbUser.AppendLine("==============================================================");
sbUser.AppendLine(Environment.NewLine);

use Environment.NewLine after each line or where you want new line

eg:-

  sbUser.AppendLine("Please find below confirmation of your registration details. If any of these details are incorrect, please email someone@somewhere.com" + Environment.NewLine);
  sbUser.AppendLine("Selected event : " + ContentPage.FetchByID(int.Parse(ddlEvent.SelectedValue)).PageTitle); 
ColinPBriggs

Windows 10 Insider preview Build 15007. The Default Line Terminator and the Environment.NewLine are both "\n". To use "\r\n" I had to create a string constant and use it instead.

Rolo

First sbUser.Appendline();

Second sbUser.Append("texto loco ");

Voila!

=)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!