Convert DotNetZip ZipFile to byte array

4.5k views Asked by At

I've built a DotNetZip ZipFile with several entries. I'd like to convert it to a byte array so I can download it using the download construct below.

   Using wrkZip As New ZipFile
        '----- create zip, add memory stream----------
       For n As Integer = 0 To wrkAr.Count - 1
           wrkFS = wrkAr(n)
           wrkZip.AddEntry(wrkFS.FileName, wrkFS.ContentStream)
       Next

   dim wrkBytes() as Byte
   dim wrkFileName as string = "Test.txt"

   ===> wrkBytes = ConvertToByteArray(wrkZip) <==== 

    context.Response.Clear()
        context.Response.ContentType = "application/force-download"
        context.Response.AddHeader("content-disposition", "attachment; filename=" & wrkFileName)
        context.Response.BinaryWrite(wrkBytes)
        wrkBytesInStream = Nothing
        context.Response.End()

I recognize that there is a ZipFile method for this:

wrkZip.Save(context.Response.OutputStream)

However, I've got a difficult bug in using that, described here:

DotNetZip download works in one site, not another

so I'm looking for a short term workaround. The short story on the bug is that the the ZipFile writes to disk fine, and downloads fine in a very similar website; it just doesn't work in the case I need it to right now.

So, how to convert a DotNetZip ZipFile to a byte array? I've looked at other answers however they don't describe this particular case of converting a whole, loaded ZipFile.

1

There are 1 answers

1
shf301 On BEST ANSWER

Use a MemoryStream to get the contents into a byte array:

Dim ms as New MemoryStream
wrkZip.Save(ms)
wrkBytes = ms.ToArray()