C#-无法访问关闭的流

问题描述

我使用iTextSharp版本5.5.13.2创建PDF的代码返回错误,“无法访问封闭的流”。 我不确定将我的代码封装在Using语句的范围内时,怎么会出现此错误。调试导致应用程序进入中断状态。 PdfWriter writer = PdfWriter.GetInstance(doc,ms);

解决方法

查看(已弃用的)iTextSharp 5.5.13.2 here的源代码,我可以找到DocWriterPdfWriter的基类)的源代码,它是{{1 }}方法here

Close
在这种情况下,

public virtual void Close() { open = false; os.Flush(); if (closeStream) os.Close(); } 是作为第二个参数传递给os(在您的情况下为PdfWriter.GetInstance)的东西。使用Ctrl + F,我可以找到ms的来源,该来源恰好是公开为closeStream here

的属性
CloseStream

public virtual bool CloseStream { get { return closeStream; } set { closeStream = value; } } 的{​​{3}}会自动调用Close

DocWriter

因此,如果您不希望public virtual void Dispose() { Close(); } 关闭PdfWriter,则需要在ms关闭之前设置writer.CloseStream = false;