4

我从字节数组在控制器中创建了一个 zip 文件,并将该 zip 文件作为文件结果返回。当我下载 zip 文件并解压缩文件时,它已损坏。我是这样做的:

byte[] fileBytes =array
MemoryStream fileStream = new MemoryStream(fileBytes);
MemoryStream outputStream = new MemoryStream();
fileStream.Seek(0, SeekOrigin.Begin);

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

outputStream.Position = 0;

FileStreamResult fileResult = new FileStreamResult(outputStream, System.Net.Mime.MediaTypeNames.Application.Zip);
fileResult.FileDownloadName = returnFileName + ".zip";

return fileResult;
4

2 回答 2

4

您可能会不幸遇到DotNetZip中的一个未解决的错误。例如,根据文件大小(https://dotnetzip.codeplex.com/workitem/14087)存在问题。

不幸的是,DotNetZip存在一些关键问题,并且该项目似乎不再得到积极维护。更好的选择是使用 SharpZipLib(如果您遵守他们基于 GPL 的许可证),或zlib 的 .NET 端口之一

如果您使用的是 .NET 4.5,则可以使用命名空间中的内置类System.IO.Compression。可以在ZipArchive该类的文档中找到以下示例:

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("========================");
                    }
                }
            }
        }
    }
}
于 2013-01-08T12:40:12.467 回答
0
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;
    }
}
于 2013-01-08T12:09:29.873 回答