尝试在C#中将csv作为电子邮件附件发送

时间:2017-03-16 20:45:43

标签: c# email-attachments streamwriter memorystream system.net.mail

当我使用StreamWriter.WriteLine时,它似乎没有向MemoryStream写任何内容。

- “数据”是以前填充的内容。它是一个对象[],包括具有Name,Date和PhoneNumber的对象。

StreamWriter sw = new StreamWriter(new MemoryStream());
CustomerReport[] customers = (CustomerReport[])data;
foreach (var d in customers)
{
    sw.WriteLine($"{d.Name},{d.Date},{d.PhoneNumber}");
}
Attachment attachment = new Attachment(sw.BaseStream, "CustomerReport.csv", "text/csv");

csv附件始终为空csv

更新: 我明白了。它实际上是MemoryStream()。 我只是设置MemoryStream(),在这种情况下是sw.BaseStream.Postion = 0

以下是工作版本:

StreamWriter sw = new StreamWriter(new MemoryStream());
CustomerReport[] customers = (CustomerReport[])data;
foreach (var d in customers)
{
    sw.WriteLine($"{d.Name},{d.Date},{d.PhoneNumber}");
    sw.Flush();
}
sw.BaseStream.Position = 0;
Attachment attachment = new Attachment(sw.BaseStream, "CustomerReport.csv", "text/csv");

1 个答案:

答案 0 :(得分:1)

尝试在foreach之后调用Flush方法:

sw.Flush();