我从字节数组中在控制器中创建一个zip文件,然后将zip文件作为fileresult返回。当我下载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;
答案 0 :(得分:4)
你可能不幸遇到 DotNetZip 中的一个漏洞。例如有问题取决于文件大小(https://dotnetzip.codeplex.com/workitem/14087)。
不幸的是, DotNetZip 存在一些关键问题,似乎不再积极维护项目。更好的替代方案是使用SharpZipLib(如果您遵守基于GPL的许可证),或.NET ports of zlib之一。
如果您使用的是.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("========================");
}
}
}
}
}
}
答案 1 :(得分: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;
}
}