Disposable:MemoryStream.Capacity在生成PDF文件时抛出了System.ObjectDisposedException的异常

时间:2015-08-31 15:07:30

标签: c# idisposable streamwriter memorystream htmltextwriter

我在生成PDF文件时使用Disposable pattern。 使用以下代码:

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();
            }
        }
    }
    ...
}

执行后:

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

在浏览MemoryStream的属性时,我会观察到以下内容:

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'

代码可能出现什么问题?

2 个答案:

答案 0 :(得分:-1)

也许编译器没有正确地包围使用块。如果明确地将using语句括起来,你会看到同样的问题吗?

编辑:由于缺少代表,无法发布评论:(。

答案 1 :(得分:-1)

问题是,你在移动到位置= 0之前刷新了流。尝试不刷新,只需注释掉printWriter.Flush()