Reputation: 3
When I use StreamWriter.WriteLine
it doesn't seem to write anything to a MemoryStream
.
-"data" is something that is previously populated. It is an object[] that includes objects that have Name, Date, and 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
.
Update:
I got it figured out. It was actually the MemoryStream()
.
I just set my MemoryStream()
which in this case is 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");
Upvotes: 0
Views: 2033