private void DownLoadAsZip(string folderName, string outFileName) { //取文件夾下文件,只取當前目錄下文件,子文件不取 string[] files = Directory.GetFiles(folderName); int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); //設置文件路徑長度,方便后續取文件夾中文件及生成子文件夾 MemoryStream outputMemStream = new MemoryStream(); ZipOutputStream zipStream = new ZipOutputStream(outputMemStream); zipStream.SetLevel(0); foreach (string filename in files) { FileInfo fi = new FileInfo(filename); string entryName = filename.Substring(folderOffset); // Makes the name in zip based on the folder //取文件名稱 entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction//格式化文件名稱 ZipEntry newEntry = new ZipEntry(entryName); //生成壓縮文件項 newEntry.DateTime = fi.LastWriteTime; // Note the zip format stores 2 second granularity newEntry.Size = fi.Length; zipStream.PutNextEntry(newEntry); //把壓縮文件項加入 壓縮文件流,應該是打開項目添加接口 // Zip the file in buffered chunks // the "using" will close the stream even if an exception occurs byte[] buffer = new byte[4096]; using (FileStream streamReader = File.OpenRead(filename)) { StreamUtils.Copy(streamReader, zipStream, buffer); //把壓縮文件項的文件流 copy 進 壓縮文件流 } zipStream.CloseEntry(); } zipStream.IsStreamOwner = false; // False stops the Close also Closing the underlying stream. zipStream.Close(); // Must finish the ZipOutputStream before using outputMemStream. //導出 Response.ContentType = "application/zip"; Response.AddHeader("content-disposition", "attachment; filename=" + HttpUtility.UrlEncode(outFileName + ".zip", System.Text.Encoding.UTF8)); outputMemStream.WriteTo(Response.OutputStream); Response.Flush(); Response.End(); }
