Search code examples
c#streamitextfilestreammemorystream

C# - Cannot access a closed stream


My code for PDF creation with iTextSharp version 5.5.13.2 is returning error, "Cannot access a closed stream." I am unsure how this error could arise as I have my code encapsulated within reaches of Using statement. Debugging results in app going to break state. PdfWriter writer = PdfWriter.GetInstance(doc, ms);


Solution

  • Looking at the source code for the (deprecated) iTextSharp 5.5.13.2 here, I can find the source for the DocWriter (base class of PdfWriter) and it's Close method here

    public virtual void Close() {
        open = false;
        os.Flush();
        if (closeStream)
            os.Close();
    }
    

    os in this case is whatever was passed as the second argument to PdfWriter.GetInstance (ms in your case). Using Ctrl + F I can find the source for closeStream, which happens to be a property exposes as CloseStream here

    public virtual bool CloseStream {
        get {
            return closeStream;
        }
        set {
            closeStream = value;
        }
    }
    

    And all together Close is automatically called by the Dispose method of DocWriter

    public virtual void Dispose() {
        Close();
    }
    

    So, if you don't want the PdfWriter to close your ms, you'll need to set writer.CloseStream = false; before your PdfWriter gets closed