İçeriğe geç

Download .zip files from MemoryStream in .NET Core MVC

This is how we can download our byte array files as a zip on .net core mvc web application.

using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;

public IActionResult DownloadDocumentsAsZip()
        {
            //get the source files
            List<byte[]> documents = new List<byte[]>();

            // the output bytes of the zip
            byte[] fileBytes = null;

            // create a working memory stream
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // create a zip
                using (ZipArchive zip = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
                {
                    // iterate through the source files
                    foreach (var f in documents)
                    {
                        // add the item name to the zip
                        ZipArchiveEntry zipItem = zip.CreateEntry("entryName");
                        // add the item bytes to the zip entry by opening the original file and copying the bytes
                        using (MemoryStream originalFileMemoryStream = new MemoryStream(f))
                        {
                            using (Stream entryStream = zipItem.Open())
                            {
                                originalFileMemoryStream.CopyTo(entryStream);
                            }
                        }
                    }
                }
                fileBytes = memoryStream.ToArray();
            }

            // download the constructed zip
            return File(fileBytes.ToArray(), "application/zip", "AllFiles.zip");
        }

İlk Yorumu Siz Yapın

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir