0
我發現了一些使用第三方DLL來完成此操作的代碼,但我希望能夠使用native .net ZipArchive。我到目前爲止的代碼是:創建一個MVC ActionResult,它將獲取一個文件列表,將它們壓縮並提供給用戶
public class ZipResult : ActionResult
{
private readonly IEnumerable<string> files;
private string fileName;
public string FileName
{
get
{
return fileName ?? "Logfiles.zip";
}
set { fileName = value; }
}
public ZipResult(params string[] files)
{
this.files = files;
}
public ZipResult(IEnumerable<string> files)
{
this.files = files;
}
public override void ExecuteResult(ControllerContext context)
{
using (var zipStream = new MemoryStream())
{
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
var entry = zip.CreateEntry("test.txt");
using (var sw = new StreamWriter(entry.Open()))
{
sw.WriteLine(
"Etiam eros nunc, hendrerit nec malesuada vitae, pretium at ligula.");
}
}
context.HttpContext
.Response.ContentType = "application/zip";
context.HttpContext
.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
zipStream.Position = 0;
zipStream.CopyTo(context.HttpContext.Response.OutputStream);
}
}
}
這工作得很好,但顯然沒有任何現有的文件實際上是添加到壓縮文件,它只需創建一個新的文本文件,並補充說。我想要的是能夠傳遞文件列表,並在將文件發回給用戶之前將它們全部添加到存檔中。這是我爲嘗試做這項工作所做的。
public class ZipResult : ActionResult
{
private readonly IEnumerable<string> files;
private string fileName;
public string FileName
{
get
{
return fileName ?? "Logfiles.zip";
}
set { fileName = value; }
}
public ZipResult(params string[] files)
{
this.files = files;
}
public ZipResult(IEnumerable<string> files)
{
this.files = files;
}
public override void ExecuteResult(ControllerContext context)
{
using (var zipStream = new MemoryStream())
{
using (var zip = new ZipArchive(zipStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
var entry = zip.CreateEntry(file);
using (var writer = new StreamWriter(entry.Open()))
{
using (var fileStream = new FileStream(file, FileMode.Open))
{
fileStream.CopyTo(writer.BaseStream);
fileStream.Flush();
fileStream.Close();
}
}
}
}
context.HttpContext
.Response.ContentType = "application/zip";
context.HttpContext
.Response.AppendHeader("content-disposition", "attachment; filename=" + FileName);
zipStream.Position = 0;
zipStream.CopyTo(context.HttpContext.Response.OutputStream);
}
}
}
此代碼不起作用。它甚至不會將一個文件添加到存檔中。我顯然錯過了一些非常明顯的東西,但我患有密碼盲症。
所有的建議和幫助非常感謝。
乾杯邁克