简体   繁体   English

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

[英]Trying to send csv as an email attachment in C#

When I use StreamWriter.WriteLine it doesn't seem to write anything to a MemoryStream . 当我使用StreamWriter.WriteLine时,似乎没有向MemoryStream写入任何内容。

-"data" is something that is previously populated. -“数据”是先前填充的内容。 It is an object[] that includes objects that have Name, Date, and PhoneNumber. 它是一个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");

However the csv attachment is always an empty csv . 但是, csv附件始终是空的csv

Update: I got it figured out. 更新:我明白了。 It was actually the MemoryStream() . 实际上是MemoryStream() I just set my MemoryStream() which in this case is sw.BaseStream.Postion = 0 我只设置了我的MemoryStream() ,在这种情况下为sw.BaseStream.Postion = 0

Below is a working version: 下面是一个工作版本:

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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM