Problem Saving Memory Streams?

Aug 24, 2009 at 8:04 AM

I must be missing something simple.

I had a problem saving memory streams to a zip file. When the file saved to disk or written to an ASP.Net response stream, the files would all have zero lengths.

With this code, all the filenames are present, but the files are zero length:

 

using (ZipFile zip = new ZipFile())
{
    foreach (var image in list)
    {
        var stream = GetStream(image);
        var entry = zip.AddEntry(image.ImageName, "", stream);
    }

    context.Response.ContentType = "application/zip";
    zip.Save(context.Response.OutputStream);

    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

 

 

This worked well:

 

using (ZipFile zip = new ZipFile())
{
    foreach (var image in list)
    {
        var stream = GetStream(image);
        byte[] bytes = stream.ToArray();
        var entry = zip.AddEntry(image.ImageName, "", bytes);
    }

    context.Response.ContentType = "application/zip";
    zip.Save(context.Response.OutputStream);

    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

FYI, the images are cached as MemoryStreams and accessed with a special object. If I did a stream.WriteTo(context.Repsonse.OutputStream) and set the appropriate contentType, the image displayed fine in the browser.

 

Coordinator
Aug 24, 2009 at 10:00 AM

Can you check the Position on each stream before adding it?   Or, try a stream.Seek(0, SeekOrigin.Begin).    If the stream cursor is at the end of the stream, you will have this problem.

 

Aug 25, 2009 at 4:17 AM

Ahhhh. I actually had that thought because I saw the position in the debugger. I tried just setting the stream.position to zero, but that didn't work. That's what I get for coding at 2am. ;-)

Awesome library! Thanks.

I was dreading doing my latest project with SharpZipLib. This was soooo much easier.

Thanks again.

Coordinator
Aug 25, 2009 at 4:42 AM

Thanks for the good words. Yeah, I agree with you on SharpZipLib. I put this library together because I didn't like it.  It was too complicated to use.   And then DotNetZip just kept getting bigger and bigger...

Coordinator
Dec 5, 2009 at 1:02 PM

also, I think you should use Response.Close() instead of HttpContext.Current.ApplicationInstance.CompleteRequest();