using Ionic.Zip
...
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
foreach (GridViewRow row in GridView1.Rows)
{
if ((row.FindControl("chkSelect") as CheckBox).Checked)
{
string filePath = (row.FindControl("lblFilePath") as Label).Text;
zip.AddFile(filePath, "Files");
}
}
Response.Clear();
Response.BufferOutput = false;
string zipName = String.Format("Zip_{0}.zip", DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=" + zipName);
zip.Save(Response.OutputStream);
Response.End();
}
您好!这部分代码可以下载压缩目录。让我们说我想要下载的文本文件的内容网格视图。有没有办法让程序下载这样的archieve而不知道或写入文件的路径?
代码应该以这种方式工作:
1. get item from gridview
2. create a text file from the content
3. add it to the zip directory
(repeat foreach item in gridview)
n. download a zipped file
答案 0 :(得分:1)
根据文档,您可以add an entry from a Stream
。因此,请考虑您目前在哪里这样做:
zip.AddFile(filePath, "Files");
而不是添加"文件"给定一个路径,你要添加一个"文件"给出了一个数据流。
因此,您可以从字符串创建流:
new MemoryStream(Encoding.UTF8.GetBytes(someString)) // or whatever encoding you use
并将其添加到Zip:
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(someString)))
{
zip.AddEntry(someFileName, stream);
// other code
zip.Save(Response.OutputStream);
}
这里需要注意的一点是,您的资源管理和处置(使用using
块)可能变得有点棘手。这是因为,根据文件:
应用程序应提供开放,可读的流;在这种情况下,它将在调用Save()或其中一个重载期间被读取。
这意味着如果您在调用.Save()
之前处置任何流,则在调用它时它将失败。您可能希望更多地查看文档,以了解是否有一种方法可以强制Zip在流程的早期读取流。否则你基本上将不得不管理一堆开放的流,直到它需要时间来保存"邮编。
修改:它看起来像文档was right there ...
如果将大量流添加到ZipFile,应用程序可能希望避免同时打开所有流。要处理这种情况,应用程序应该使用AddEntry(String,OpenDelegate,CloseDelegate)重载。
这会稍微复杂一些,需要您在代理中手动打开/关闭/处理您的流。因此,在构建逻辑时,这取决于您是否优于嵌套using
块。它可能取决于您计划使用的流量。