簡體   English   中英

c#下載由Web應用程序創建的文件的zip存檔

[英]c# downloading a zip archieve of files created by web application

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();
    }

你好! 這部分代碼用於下載壓縮目錄。 假設我要下載的文本文件包含一個gridview。 有沒有一種方法可以使程序在不知道或不寫文件路徑的情況下下載此類文件?

該代碼應以這種方式工作:

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

根據文檔,您可以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在此過程的早期讀取流。 否則,您基本上必須管理一堆開放流,直到需要“保存” Zip為止。


編輯:看起來文檔就在那里 ...

在將大量流添加到ZipFile的情況下,應用程序可能希望避免同時保持所有流打開。 要處理這種情況,應用程序應使用AddEntry(String,OpenDelegate,CloseDelegate)重載。

這會稍微復雜一點,將需要您在代理中手動打開/關閉/處理流。 因此,這取決於您構建邏輯是否比嵌套您的using塊更可取。 這可能取決於您計划使用多少個流。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM