how do I zip multiple files using GZipStream in c#

后端 未结 2 880
逝去的感伤
逝去的感伤 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<String> files =  new List<String>();
            files.Add(string1);
            files.Add(string2);
    
            byte[] buffer = CompressStringToFile("myfile.zip", files);
    
            return File(buffer, "application/zip");
        }
    
    
    private byte[] CompressStringToFile(string fileName, List<string> 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;
        }
    
    0 讨论(0)
  • 2021-01-03 12:12

    You can't do this with a GZipStream. You'll need a 3rd party library. Probably the best one out there is SharpZipLib. I've used this on projects in the past, and it's very easy to use. Plus it's been around for a while so should be pretty stable and bug-free.

    0 讨论(0)
提交回复
热议问题