1

I want to create a zip-file and return it to the browser so that it downloads the zip to the downloads-folder.

              var images = imageRepository.GetAll(allCountryId);

        using (FileStream f2 = new FileStream("SudaAmerica", FileMode.Create))
        using (GZipStream gz = new GZipStream(f2, CompressionMode.Compress, false))
        {
            foreach (var image in images)
            { 
                gz.Write(image.ImageData, 0, image.ImageData.Length);
            }
            return base.File(gz, "application/zip", "SudaAmerica");
        }

i have tried the above but then i get an error saying the stream is disposed.

Is this possible or should i use another library then gzipstream?

Daniel Gustafsson
  • 1,725
  • 7
  • 37
  • 78
  • Copy the gz stream into a memory stream and don't close it. The File handler will do that for you. – Vince Jan 08 '16 at 21:54

1 Answers1

4

The problem here is exactly what it says: you are handing it something based on gz, but gz gets disposed the moment you leave the using.

One option would be to wait until outside the using block, then tell it to use the filename of the thing you just wrote ("SudaAmerica"). However, IMO you shouldn't actually be writing a file here at all. If you use a MemoryStream instead, you can use .ToArray() to get a byte[] of the contents, which you can use in the File method. This requires no IO access, which is a win in about 20 different ways. Well, maybe 3 ways. But...

var images = imageRepository.GetAll(allCountryId);
using (MemoryStream ms = new MemoryStream())
{
    using (GZipStream gz = new GZipStream(ms, CompressionMode.Compress, false))
    {
        foreach (var image in images)
        { 
            gz.Write(image.ImageData, 0, image.ImageData.Length);
        }
    }
    return base.File(ms.ToArray(), "application/zip", "SudaAmerica");
}

Note that a gzip stream is not the same as a .zip archive, so I very much doubt this will have the result you want. Zip archive creation is available elsewhere in the .NET framework, but it is not via GZipStream.

You probably want ZipArchive

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • 1
    Thanks for pointing me in the right direction! ZipArchive worked perfectly :) I used the example from this thread: http://stackoverflow.com/questions/17217077/create-zip-file-from-byte – Daniel Gustafsson Jan 08 '16 at 22:05
  • @DanielGustafsson no problem! thanks for being receptive to the hint - sometimes people react badly if you point out this type of thing – Marc Gravell Jan 08 '16 at 22:07
  • @DanielGustafsson note: if `image.ImageData` is a `byte[]`, the *innermost* `MemoryStream` in that linked example is redundant - you can use a `Write` very similar to your `gz.Write(...)`, but `zipEntryStream.Write(...)`. – Marc Gravell Jan 08 '16 at 22:09