clueless7788
clueless7788

Reputation: 3

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.

-"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

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

Try calling Flush method after foreach:

sw.Flush();

Upvotes: 1

Related Questions