Disposable: MemoryStream.Capacity threw an exception of System.ObjectDisposedException when generating PDF file

3.6k Views Asked by At

I'm using a Disposable pattern when generating PDF file. The following code is used:

public partial class WriteNotes : System.Web.UI.Page
{
     ...
     protected override void Render(System.Web.UI.HtmlTextWriter writer)
     {
        ...
        using (System.IO.MemoryStream printStream = new System.IO.MemoryStream())
        using (System.IO.StreamWriter printStreamWriter = new System.IO.StreamWriter(printStream))
        using (System.Web.UI.HtmlTextWriter printWriter = new System.Web.UI.HtmlTextWriter(printStreamWriter))
        {
            base.Render(printWriter);
            printWriter.Flush();
            using (System.IO.StreamReader myStreamReader = new System.IO.StreamReader(printStream))
            {
               myStreamReader.BaseStream.Position = 0;
               Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlStream(myStreamReader.BaseStream, System.Text.Encoding.Default, HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.Url.PathAndQuery, "/"));
               HttpContext.Current.Response.Clear();
               HttpContext.Current.Response.ContentType = "application/pdf";
               pdfDocument.Save(HttpContext.Current.Response.OutputStream);
               HttpContext.Current.Response.Flush();
               HttpContext.Current.Response.End();
            }
        }
    }
    ...
}

After executing:

Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromHtmlStream(myStreamReader.BaseStream,   System.Text.Encoding.Default,HttpContext.Current.Request.Url.ToString().Replace(HttpContext.Current.Request.Url.PathAndQuery, "/"));

I observe the following when go through the MemoryStream's properties:

Capacity: 'printStream.Capacity' threw an exception of type 'System.ObjectDisposedException'
Length: 'printStream.Length' threw an exception of type 'System.ObjectDisposedException'
Position: 'printStream.Position' threw an exception of type 'System.ObjectDisposedException'

What can possibly be wrong with the code?

2

There are 2 best solutions below

2
Dimenus On

Maybe the compiler isn't bracketing the using blocks correctly. Are you seeing the same issue if you explicitly bracket the using statements out?

Edit: Can't post as comment due to lack of rep :(.

0
Philippe Paré On

The problem is, you did flush the stream before moving to the position = 0. Try without flushing, just comment out the printWriter.Flush().