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

Trying to send csv as an email attachment in C#

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

-"data" 是以前填充的东西。它是一个 object[],包括具有 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");

尝试在 foreach:

之后调用 Flush 方法
sw.Flush();