3

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.

Andrei Ivascu
  • 1,172
  • 8
  • 17
  • How did you create that workbook? From as file or from a stream or created it from scratch? – rene Dec 31 '16 at 11:50
  • I am creating it from a stream (template excel file). I tried to create one from scratch and it generates a malformatted excel file. – Andrei Ivascu Dec 31 '16 at 11:55
  • If it is created from a stream I expect your code to take [this else](https://github.com/ClosedXML/ClosedXML/blob/develop/ClosedXML/Excel/XLWorkbook.cs#L553) which makes me believe your original stream should be available, as in, not disposed. – rene Dec 31 '16 at 12:00
  • @rene you are correct. It seems that disposing the original stream was the problem. It's weird that the workbook does not make a deep copy of the stream (perhaps to save space in memory?). However the xlsx is still corrupted seemingly related to this [issue](https://github.com/ClosedXML/ClosedXML/issues/135). Could you write an answer so I can mark it as a correct answer? – Andrei Ivascu Dec 31 '16 at 12:24

1 Answers1

3

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.

rene
  • 41,474
  • 78
  • 114
  • 152
  • Indeed disposing the original Stream seemed to be the problem since the Workbook keeps a reference to the [original stream](https://github.com/ClosedXML/ClosedXML/blob/develop/ClosedXML/Excel/XLWorkbook.cs#L711). – Andrei Ivascu Dec 31 '16 at 12:47
  • What if I created my workbook from byte[]? I have no steam in this case – Nick Farsi Jan 29 '21 at 21:34
  • @NickFarsi any `byte[]` instance goes into a ctor on MemoryStream like `new MemoryStream(byteArray);`. But be careful if you want to save back to that same stream as your stream can't grow if you use that ctor. – rene Jan 29 '21 at 21:37