DEV Community

Rasma Raj
Rasma Raj

Posted on

Download multiple files in zipped format

Use System.IO.Compression class for compressing the file in .Zip format

=> Create a instance of the MemoryStream .
=> Create Zipped folder in memory
=> Use archive.CreateEntry method to add files into the zip folder
=> Add content into the created files
=> Now the zipped folder with all files stored in the memory instance
=> Then return the file , the save As file dialogue appears in the window.

using System.IO.Compression;

public void DownloadFilesInZip()
{
 var _ListOfFiles=new List<Tuple<int,byte[],string>>()
{
new Tuple<int,byte[],string>(1,F1,FileName1),
new Tuple<int,byte[],string>(2,F2,FileName2),
new Tuple<int,byte[],string>(3,F3,FileName3)
};

using (MemoryStream ms = new MemoryStream())
{
using (var archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
     {
     foreach (var _file in _ListOfFiles)
        {
     var entry = archive.CreateEntry(_file.Item3, CompressionLevel.Fastest);

     using (var zipStream = entry.Open())
         {
zipStream.Write(_file .Item2, 0, _file .Item2.Length);
         }

        }
    }
string _FileName = $"DateTime.Now.ToString("ddMMyyyy")}.zip";
return File(ms.ToArray(), "application/zip", _FileName);
                    }

}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)