Search code examples
php-ziparchive

how to convert byte array to zip archive in c#?


I have a byte array of ziparchive in database. when i retrieve the data from database and try to convert back to Ziparchive it throws an error. Is there any way to convert to zipArchive from the byte array?


Solution

  • From this answer I think it is possible to convert your stream byte array to zip archive:

    using (var compressedFileStream = new MemoryStream()) {
        //Create an archive and store the stream in memory.
        using (var zipArchive = new ZipArchive(compressedFileStream, ZipArchiveMode.Update, false)) {
            foreach (var caseAttachmentModel in caseAttachmentModels) {
                //Create a zip entry for each attachment
                var zipEntry = zipArchive.CreateEntry(caseAttachmentModel.Name);
    
                //Get the stream of the attachment
                using (var originalFileStream = new MemoryStream(caseAttachmentModel.Body)) {
                    using (var zipEntryStream = zipEntry.Open()) {
                        //Copy the attachment stream to the zip entry stream
                        originalFileStream.CopyTo(zipEntryStream);
                    }
                }
            }
    
        }
    
        return new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };
    }
    

    Here, with the line new FileContentResult(compressedFileStream.ToArray(), "application/zip") { FileDownloadName = "Filename.zip" };, if you already converted into zip file then you can convert your stream byte array into zip archive like this:

    new FileContentResult(your_stream_byte_array, "application/zip") { FileDownloadName = "Filename.zip" };