Compress file with dotnetzip, and when open it is corrupted

风流意气都作罢 提交于 2019-12-01 19:46:29

You might be unlucky hitting one of the open bugs in DotNetZip. There is e.g. an issue depending on the file size (https://dotnetzip.codeplex.com/workitem/14087).

Unfortunately, DotNetZip has some critical issues and the project seems no longer be actively be maintained. Better alternatives would be to use SharpZipLib (if you comply with their GPL-based license), or one of the .NET ports of zlib.

If you are on .NET 4.5 you can use the built-in classes in the System.IO.Compression namespace. The following sample can be found in the documentation of the ZipArchive class:

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            using (var zipToOpen = 
                new FileStream(@"c:\tmp\release.zip", FileMode.Open))
            {
                using (var archive = 
                     new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                {
                    var readmeEntry = archive.CreateEntry("Readme.txt");
                    using (var writer = new StreamWriter(readmeEntry.Open()))
                    {
                            writer.WriteLine("Information about this package.");
                            writer.WriteLine("========================");
                    }
                }
            }
        }
    }
}
public class HomeController : Controller
{
    public FileResult Index()
    {
        FileStreamResult fileResult = new FileStreamResult(GetZippedStream(), System.Net.Mime.MediaTypeNames.Application.Zip);
        fileResult.FileDownloadName = "result" + ".zip";
        return fileResult;
    }

    private static Stream GetZippedStream()
    {
        byte[] fileBytes = Encoding.ASCII.GetBytes("abc");
        string returnFileName = "something";

        MemoryStream fileStream = new MemoryStream(fileBytes);
        MemoryStream resultStream = new MemoryStream();

        using (ZipFile zipFile = new ZipFile())
        {
            zipFile.AddEntry(returnFileName, fileStream);
            zipFile.Save(resultStream);
        }

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