当我使用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");