.net - StringBuilder.AppendLine() 不会创建新行

标签 .net vb.net string email stringbuilder

发生错误时我正在生成电子邮件。我正在使用 StringBuilder.AppendLine() 和 StringBuilder.AppendLine(String) 构建电子邮件正文,但是我的电子邮件正文显示为很长的一行没有换行符。

例如:

Dim ErrorsStringBuilder As New StringBuilder
ErrorsStringBuilder.AppendLine(String.Format("Status : {0}  Message : {1}", Results.Status, Results.ErrorMessage))
ErrorsStringBuilder.AppendLine(String.Format("Failed : {0}  Total : {1}", Results.FailedCount, Results.TotalCount))
ErrorsStringBuilder.AppendLine("Batch #: " & Results.BatchNumber)
ErrorsStringBuilder.AppendLine()
ErrorsStringBuilder.AppendLine("Individual Errors:")
ErrorsStringBuilder.AppendLine()
For Each FailedRecord .......
  ErrorsStringBuilder.AppendLine(String.Format("Failed Record ID : {0}  Message : {1}", FailedRecord.ID, FailedRecord.ErrorText))
Next

这是 MSDN 分别对 .AppendLine().AppendLine(String) 的描述。

Appends the default line terminator to the end of the current StringBuilder object.

Appends a copy of the specified string followed by the default line terminator to the end of the current StringBuilder object.

我的问题是:为什么没有换行符? 为什么没有应用默认的行终止符?我是否误解了描述?

ps。我确实看过this question但没有解释原因。

而且我知道我可以使用 System.Environment.NewLine"\n" 来获取换行符。

最佳答案

您的电子邮件正文似乎属于 HTML 类型但你正在渲染simple text -

如果你真的希望它是 simple text然后在您的电子邮件对象集中 IsBodyHtml = false它将渲染新行而不修改您的 StringBuilder 代码 -

MailMessage mail = new MailMessage();
mail.IsBodyHtml = false;

如果您只需要 HTML,请尝试在每行后面添加 -

ErrorsStringBuilder.AppendLine("<br />");

实际上,您正在尝试构建 HTML 输出。

在 HTML 中,如果你写 -

<html>
<body>
Hi,

How are you?
</body>
</html>

这会导致 -

Hi, How are you? 

为了使其工作,您应该将这两个语句包含在两个不同的 block 元素中 -

在本例中,我使用段落 -

<html>
<body>
<p>Hi,</p>

<p>How are you?</p>
</body>
</html>

现在这将导致 -

Hi,

How are you?

在您的情况下,您需要弄清楚 HTML 来呈现所需的输出。否则使用<br />作为解决方法。

带有 <p> 的 HTML 示例标签 -

Dim ErrorsStringBuilder As New StringBuilder
ErrorsStringBuilder.AppendLine(String.Format("<p>Status : {0}  Message : {1}</p>", Results.Status, Results.ErrorMessage))
ErrorsStringBuilder.AppendLine(String.Format("<p>Failed : {0}  Total : {1}</p>", Results.FailedCount, Results.TotalCount))
ErrorsStringBuilder.AppendLine("<p>Batch #: </p>" & Results.BatchNumber)
ErrorsStringBuilder.AppendLine()
ErrorsStringBuilder.AppendLine("<p>Individual Errors:</p>")
ErrorsStringBuilder.AppendLine()
For Each FailedRecord .......
  ErrorsStringBuilder.AppendLine(String.Format("<p>Failed Record ID : {0}  Message : {1}</p>", FailedRecord.ID, FailedRecord.ErrorText))
Next

关于.net - StringBuilder.AppendLine() 不会创建新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16334244/

相关文章:

vb.net - 获取 Debug模式下的工作表计数 - MS Excel PIA

java - 我的数组出现空指针异常?

java - 将字符串类型引用标记为 volatile 安全吗?

c# - 我习惯于让 IDE 在 vb.net 下为我创建事件签名,如何使用 C# 来创建事件签名?

javascript - 具有单个元素的 Javascript 数组

vb.net - 检测 VB.NET 上的 Enter 按键

R:根据索引列表粘贴一些字符串向量元素

c# - 在 C# 中获取特定服务的 CPU 使用率

c# - 如何防止代码契约自动创建前提条件检查?

c# - MVC 4 列表模型绑定(bind)如何工作?