发生错误时我正在生成电子邮件。我正在使用 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/