title: PdfGenerator EmailMessage EmailAttachment - Cannot access a closed Stream
body: <p>An error <code>System.ObjectDisposedException</code> with message <code>Cannot access a closed Stream</code> is being thrown when attempting to attach and send an <code>System.IO.MemoryStream</code> <code>EmailAttachment</code> to an <code>EmailMessage</code>. The attachment is being generated using <a href="https://www.nuget.org/packages/HtmlRenderer.PdfSharp" rel="nofollow noreferrer">HtmlRenderer.PdfSharp</a>. The attaching and sending is being done within a using statement.</p>
  
  <pre><code>using (MemoryStream ms = new MemoryStream())
  {
      var pdf = PdfGenerator.GeneratePdf("&lt;html&gt;&lt;body&gt;foo&lt;/body&gt;&lt;/html&gt;", PdfSharp.PageSize.Letter);
      // 2nd argument is to NOT close stream
      pdf.Save(ms, false);
  
      EmailMessage em = new EmailMessage();
      em.EmailFormat = EmailFormatEnum.Html;
      em.From = "no-reply@foo.com";
      em.Recipients = "foo.bar@baz.net";
      em.Subject = "Attachment Name";
      em.Body = "There is an attachment";
  
      var attachment = new EmailAttachment(ms, "foo.pdf");
      em.Attachments.Add(attachment);
  
      // SiteContext.CurrentSiteName argument is just a site name required for Kentico CMS
      // true argument is send immediately
      EmailSender.SendEmail(SiteContext.CurrentSiteName, em, true);    
  }
  </code></pre>
  
  <p>If I do the following instead, it is successful the error does not occur as long as I do not attempt to <code>ms.Dispose()</code> within the <code>try</code> block:</p>
  
  <pre><code>MemoryStream ms = new MemoryStream();
  try
  {
      var pdf = PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
      pdf.Save(ms, false);
  
      EmailMessage em = new EmailMessage();
      em.EmailFormat = EmailFormatEnum.Html;
      em.From = "no-reply@foo.com";
      em.Recipients = "foo.bar@baz.net";
      em.Subject = "Attachment Name";
      em.Body = "There is an attachment";
  
      var attachment = new EmailAttachment(ms, "foo.pdf");
      em.Attachments.Add(attachment);
  
      EmailSender.SendEmail(SiteContext.CurrentSiteName, em, true);
  }
  catch (Exception)
  {
      ms.Dispose();
  }
  </code></pre>
  
  <p>The concern with the 2nd approach is that the <code>MemoryStream</code> is not being explicitly disposed. Is the <code>MemoryStream</code> inherently being disposed with this approach? If put <code>ms.Dispose();</code> <strong>after</strong> this entire block the same <code>Cannot access a closed Stream</code> occurs. Is this a memory leak waiting to happen? How can I dispose the <code>MemoryStream</code> without closing the stream to allow the email message to send the attachment?</p>
  
  <p>Is this an issue with needing to somehow wait for <code>SendEmail()</code> to actually execute it's functionality?</p>
  
  <p>Thank you for any help you can provide.</p>