how do I zip multiple files using GZipStream in c#

北战南征 提交于 2019-11-30 16:09:44

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.

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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!