如何生成临时Zip文件,然后在下载后自动删除它?

Ibr*_*GUN 4 c# asp.net zip

我有一个下载页面,其中有3个下载选项:Word,Zip和PDF.有一个包含.doc文件的文件夹.当用户单击页面上的Zip选项时,我希望ASP.NET将包含文件的.doc文件夹压缩到临时.zip文件中.然后客户端将从服务器下载它.用户下载完成后,临时Zip文件应自行删除.

我如何使用ASP.NET 2.0 C#执行此操作?

注意:我知道如何使用C#ASP.NET 2.0压缩和解压缩文件并从系统中删除文件.

Che*_*eso 8

使用DotNetZip,您可以将zip文件直接保存到Response.OutputStream.不需要临时Zip文件.

    Response.Clear();
    // no buffering - allows large zip files to download as they are zipped
    Response.BufferOutput = false;
    String ReadmeText= "Dynamic content for a readme file...\n" + 
                       DateTime.Now.ToString("G");
    string archiveName= String.Format("archive-{0}.zip", 
                                      DateTime.Now.ToString("yyyy-MMM-dd-HHmmss")); 
    Response.ContentType = "application/zip";
    Response.AddHeader("content-disposition", "attachment; filename=" + archiveName);
    using (ZipFile zip = new ZipFile())
    {
        // add a file entry into the zip, using content from a string
        zip.AddFileFromString("Readme.txt", "", ReadmeText);
        // add the set of files to the zip
        zip.AddFiles(filesToInclude, "files");
        // compress and write the output to OutputStream
        zip.Save(Response.OutputStream);
    }
    Response.Flush();
Run Code Online (Sandbox Code Playgroud)


Ibr*_*GUN 0

我通过将其添加到流代码的末尾来解决我的问题:

Response.Flush();
Response.Close();
if(File.Exist(tempFile))
{File.Delete(tempFile)};
Run Code Online (Sandbox Code Playgroud)