ClosedXml Cannot access a closed Stream

2.4k views Asked by At

I am getting the "Cannot access a closed Stream" when I am trying to save a ClosedXML Workbook (XLWorkbook) to a memory stream.

    public byte[] GetStream()
    {
        using (var stream = new MemoryStream())
        {
            Workbook.SaveAs(stream);

            return stream.ToArray();
        }
    }

As far as I can understand there is a problem within the ClosedXml library since the stream has been created just before accessing the save method.

1

There are 1 answers

3
rene On BEST ANSWER

It depends on how you created your Workbook. If it was created from a Stream it will access that original stream during the save operation.

So the exception is not due to your memorystream you supplied in the save method, it is the original stream that is the culprit. Make sure you keep that stream available until all operations you want to do on the Workbook are completed.