My main question is if I pass object to a function that are using a MemoryStream how to I go about clearing the memorystream? See my code below.
In more detail: I'm trying to send multiple emails while creating PDFs on the fly using iTextSharper. I want to make sure that I'm not doing something wrong with the MemoryStream here. I can't use a using statement because when I do my EmailPDF function says the connections are closed, also if I don't use a new MemoryStream for each PDF creation it overrides the previously created one.
I'm adding the pdfs to an attachment and then adding the attachments to a list. I then use that list to add the attachment to a mailmessage. I then send the message.
private void EmailPDF(List<String> lstFields)
{
MailMessage mm = new MailMessage("fromemailaddress", "toemailaddress")
{
Subject = "Test Email",
IsBodyHtml = true,
Body = "Testing email"
};
SmtpClient smtp = new SmtpClient
{
Host = "xxx.xxx.xxx.xxx"
};
List<System.Net.Mail.Attachment> attachments = FillAttachmentList(lstFields);
foreach (System.Net.Mail.Attachment attach in attachments)
{
mm.Attachments.Add(attach);
}
smtp.Send(mm);
attachments.Clear();
}
private List<System.Net.Mail.Attachment> FillAttachmentList(List<String> lstFields)
{
List<System.Net.Mail.Attachment> attachments = new List<System.Net.Mail.Attachment>();
foreach (String strField in lstFields)
{
MemoryStream output = new MemoryStream();
Document doc = new Document(PageSize.LETTER, 25, 25, 25, 25);
try
{
String text = System.IO.File.ReadAllText(@"C:\PDFDirectory\" + strField + ".html");
StringReader html = new StringReader(text);
PdfWriter wri = PdfWriter.GetInstance(doc, output);
doc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(wri, doc, html);
wri.CloseStream = false;
doc.Close();
attachments.Add(new Attachment(output, strField + ".pdf"));
output.Position = 0;
}
catch (Exception ex)
{
}
}
return attachments;
}
create a class
rewrite your
FillAttachmentList(lstFields);
method to provide a List<MyAttachment>;instead of
attachments.Clear();
write:In fact you should implement a
MyAttachmentCollection : IEnumerable<MyAttachment>, IDisposable
.