I am using NPOI to create an excel report from a template, write the workbook to MemoryStream and then attach it to a MailMessage in C#. My report is being generated OK, I can see it picks up the sheets fine in debug. But when I write it to MemoryStream, and try to attach it, the Attachment object says Size: -1 under ContentDisposition property. I thought setting the MemoryStream object reader position to 0 would solve this, but no luck.
MailMessage mm = new MailMessage("DoNotReply@testmail.com", "myself@testmail.com");
mm.Subject = "Reports for October, 2015";
mm.Body = "Attached below is the report.";
using (var memStream = new MemoryStream())
{
HSSFWorkbook closedReport = getClosedReport();
closedReport.Write(memStream);
memStream.Position = 0;
Attachment att1 = new Attachment(memStream, "ClosedReport.xls");
att1.ContentType = new System.Net.Mime.ContentType("application/vnd.ms-excel");
mm.Attachments.Add(att1);
memStream.Close();
}
My MemoryStream object has a length of 30,720 so I believe the report is being written to it.
Played around with this code snippet in a unit test project and I couldn't get the ContentDisposition property to change from -1.
Did however get the MemoryStream populated with data, and switching between memStream.Position = 0
to memStream.Seek(0, SeekOrigin.Begin);
didn't seem to help.
I did notice that the memStream.Close was clearing out the Attachment.ContentStream property.
Try sending the message before closing the memory stream where the attachment data is stored.