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

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

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

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

使用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(); 

表格从数据库下载和Zip和Complate下载删除使用此代码在类中需要使用ICSharpCode.SharpZipLib.Zip

  if (ds.Tables[0].Rows.Count > 0) { // Create the ZIP file that will be downloaded. Need to name the file something unique ... string strNow = String.Format("{0:MMM-dd-yyyy_hh-mm-ss}", System.DateTime.Now); ZipOutputStream zipOS = new ZipOutputStream(File.Create(Server.MapPath("~/TempFile/") + strNow + ".zip")); zipOS.SetLevel(5); // ranges 0 to 9 ... 0 = no compression : 9 = max compression // Loop through the dataset to fill the zip file foreach (DataRow dr in ds.Tables[0].Rows) { byte[] files = (byte[])(dr["Files"]); //FileStream strim = new FileStream(Server.MapPath("~/TempFile/" + dr["FileName"]), FileMode.Create); //strim.Write(files, 0, files.Length); //strim.Close(); //strim.Dispose(); ZipEntry zipEntry = new ZipEntry(dr["FileName"].ToString()); zipOS.PutNextEntry(zipEntry); zipOS.Write(files, 0, files.Length); } zipOS.Finish(); zipOS.Close(); FileInfo file = new FileInfo(Server.MapPath("~/TempFile/") + strNow + ".zip"); if (file.Exists) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name); Response.AddHeader("Content-Length", file.Length.ToString()); Response.ContentType = "application/zip"; Response.WriteFile(file.FullName); Response.Flush(); file.Delete(); Response.End(); } } 

您需要手动将zip文件流式传输给用户,然后在完成流式传输时删除该文件。

 try { Response.WriteFile( "path to .zip" ); } finally { File.Delete( "path to .zip" ); } 

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

 Response.Flush(); Response.Close(); if(File.Exist(tempFile)) {File.Delete(tempFile)};