how do I zip multiple files using GZipStream in c#

后端 未结 2 897
逝去的感伤
逝去的感伤 2021-01-03 11:59

I have created multiple csv files using datatable and want to zip all those file into one single zip file. Which is i\'m doing all at dynamically.

I tried following

2条回答
  •  难免孤独
    2021-01-03 12:04

    You will need to install the NuGet package DotNetZip.

    This will work for you:

    public ActionResult DownloadFile()
        {
            string string1 = "value1, value2, value3, value4";
            string string2 = "value10, value20, value30, value40";
    
    
            List files =  new List();
            files.Add(string1);
            files.Add(string2);
    
            byte[] buffer = CompressStringToFile("myfile.zip", files);
    
            return File(buffer, "application/zip");
        }
    
    
    private byte[] CompressStringToFile(string fileName, List content)
        {
            byte[] result = null;
            int count = 0;
    
            using (var ms = new MemoryStream())
            {
                using (var s = new ZipOutputStream(ms))
                {
                    foreach (string str in content)
                    {
                        s.PutNextEntry(String.Format("entry{0}.txt", count++));
                        byte[] buffer = Encoding.UTF8.GetBytes(str);
                        s.Write(buffer, 0, buffer.Length);
                    }
                }
    
                result = ms.ToArray();
            }
    
            return result;
        }
    

提交回复
热议问题