首页 > 解决方案 > c# 压缩多个文件并下载 - 无法在 Windows 资源管理器中打开文件

问题描述

我使用 SharpZipLib 压缩多个文件并将它们下载到我的 asp.net c# web 应用程序中。下载后我无法打开 zip 存档。Windows 错误消息是:

Windows 无法打开该文件夹。压缩(zipped)文件夹“filename.zip”无效。

这是我的代码

        if (Session["lstFilesToZip"] != null)
        {
            List<string> filesToZip = (List<string>)Session["lstFilesToZip"];

            if (filesToZip.Count > 0)
            {    
                Response.AddHeader("Content-Disposition", "attachment; filename=fileName.zip");
                Response.ContentType = "application/zip";

                using (var zipStream = new ZipOutputStream(Response.OutputStream))
                {
                    foreach (string filePath in filesToZip)
                    {
                        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);

                        var fileEntry = new ZipEntry(Path.GetFileName(filePath))
                        {
                            Size = fileBytes.Length
                        };

                        zipStream.PutNextEntry(fileEntry);
                        zipStream.Write(fileBytes, 0, fileBytes.Length);
                    }

                    zipStream.Flush();                        
                    zipStream.Close();                        
                }
            }
        }

我已经尝试添加

zipStream.Dispose();
zipStream.Finish();

没有成功。

也许有人可以帮忙。我找不到问题。

标签: c#asp.netdownloadzipsharpziplib

解决方案


推荐阅读