一次性:MemoryStream.Capacity抛出系统异常.生成PDF文件时抛出异常

本文关键字:PDF 生成 文件 抛出异常 异常 系统 MemoryStream Capacity 一次性 | 更新日期: 2023-09-27 18:10:37

我在生成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'

代码可能有什么问题?

一次性:MemoryStream.Capacity抛出系统异常.生成PDF文件时抛出异常

可能编译器没有正确地将using块括起来。如果显式地将using语句括起来,您是否会看到同样的问题?

编辑:由于缺少rep,不能作为评论发布:(.

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