Downloading of zip file through ASP.NET MVC using DotNetZip

前端 未结 5 906
小蘑菇
小蘑菇 2020-12-03 04:03

I have created a text file in a folder and zipped that folder and saved @same location for test purpose. I wanted to download that zip file directly on user machine after it

5条回答
  •  时光说笑
    2020-12-03 04:42

    just a fix to Klaus solution: (as I can not add comment I have to add another answer!)

    The solution is great but for me it gave corrupted zip file and I realized that it is because of return is before finalizing zip object so it did not close zip and result in a corrupted zip.

    so to fix we need to just move return line after using zip block so it works. the final result is :

    /// 
    ///     Zip a file stream
    /// 
    ///  MemoryStream with original file 
    ///  Name of the file in the ZIP container 
    ///  Return byte array of zipped file 
    private byte[] GetZippedFiles(MemoryStream originalFileStream, string fileName)
    {
        using (MemoryStream zipStream = new MemoryStream())
        {
            using (ZipArchive zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
            {
                var zipEntry = zip.CreateEntry(fileName);
                using (var writer = new StreamWriter(zipEntry.Open()))
                {
                    originalFileStream.WriteTo(writer.BaseStream);
                }
            }
            return zipStream.ToArray();
        }
    }
    
    /// 
    ///     Download zipped file
    /// 
    [HttpGet]
    public FileContentResult Download()
    {
        var zippedFile = GetZippedFiles(/* your stream of original file */, "hello");
        return File(zippedFile, // We could use just Stream, but the compiler gets a warning: "ObjectDisposedException: Cannot access a closed Stream" then.
                    "application/zip",
                    "sample.zip");
    }
    

提交回复
热议问题