Dictionary<string, Stream> streams = new Dictionary<string, Stream> (); Stream streamWriter = null; //將所有文件流在循環中加進,根據自己情況來寫
streamWriter = File.Open(filePath, FileMode.Open);
streams.Add(strName, streamWriter);
//下面可以直接復制粘貼 MemoryStream ms = new MemoryStream(); ms = PackageManyZip(streams); byte[] bytes = new byte[(int)ms.Length]; ms.Read(bytes, 0, bytes.Length); ms.Close(); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載文件而不是打開 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("打包文檔.zip", System.Text.Encoding.UTF8)); Response.BinaryWrite(bytes); Response.Flush();
/// <summary> /// 將多個流進行zip壓縮,返回壓縮后的流 /// </summary> /// <param name="streams">key:文件名;value:文件名對應的要壓縮的流</param> /// <returns>壓縮后的流</returns> static MemoryStream PackageManyZip(Dictionary<string, Stream> streams) { byte[] buffer = new byte[6500]; MemoryStream returnStream = new MemoryStream(); var zipMs = new MemoryStream(); using (ZipOutputStream zipStream = new ZipOutputStream(zipMs)) { zipStream.SetLevel(9); foreach (var kv in streams) { string fileName = kv.Key; using (var streamInput = kv.Value) { zipStream.PutNextEntry(new ZipEntry(fileName)); while (true) { var readCount = streamInput.Read(buffer, 0, buffer.Length); if (readCount > 0) { zipStream.Write(buffer, 0, readCount); } else { break; } } zipStream.Flush(); } } zipStream.Finish(); zipMs.Position = 0; zipMs.CopyTo(returnStream, 5600); } returnStream.Position = 0; return returnStream; }