Entry.Extract, Cannot access a closed Stream.

Sep 22, 2010 at 8:04 PM

I have the following code on v1.9:

if(StosZipFile.ContainsEntry(StosFileName))
{
    ZipEntry entry = StosZipFile[StosFileName];
    Byte[] buffer = new Byte[entry.UncompressedSize];
    MemoryStream memStream = new MemoryStream(buffer);
 
    //Fails with "Cannot access a closed stream
    entry.Extract(memStream);

    ...
}

I'm hoping I'm missing something obvious, but no matter how I create the memory stream I get that error.  I can write my own byte array to the stream without problems.

Any ideas?
Sep 22, 2010 at 8:06 PM

I also tried passing the Uncompressed size directly to the MemoryStream constructor.

Sep 22, 2010 at 8:17 PM

Argh... nevermind.  The problem is that I closed the stream used to load the ZipFile in a completely different function:

Stream responseStream = response.GetResponseStream();

Byte[] buffer = Global.ReadToBuffer(responseStream, response.ContentLength);

MemoryStream memStream = new MemoryStream(buffer);

zipFile = ZipFile.Read(memStream);

responseStream.Close();

//Problem, ZipFile takes a reference and expects it to remain open
memStream.Close();

How can I know when it is OK to close the memory stream if the ZipFile is going to hold a reference to it?  Can we ask the ZipFile to make a copy of the data instead?

Coordinator
Sep 23, 2010 at 12:39 AM
You should reference the ZipFile within a using clause. This is not optional. See the documentation on the ZipFile object for an explanation. The examples in the documentation show what this looks like. (or look at the test code in the DotNetZip source release) The MemoryStream can be closed after the ZipFile goes out of the using scope. Actually, you can use the MemoryStream within its own using clause, too. It's good form to use "using" with streams.