//DLL
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;app
public void DownloadZipFile(string id) { string zipFilePath = Property.GetFileUrlString("免冠照片temp", Property.FileEnum.zip); if (!Directory.Exists(Server.MapPath("~/Template/Template/Zip"))) { Directory.CreateDirectory(Server.MapPath("~/Template/Template/Zip")); } try { List<string> filenames = new List<string>(); string filesPath = string.Empty; foreach (var item in id.Split(',')) { var result = _pictureAppServices.FirstOrDefault(p => p.Id.ToString() == item); if (result != null) { filesPath = result.Url; } filenames.Add(Server.MapPath("~/" + filesPath)); // filenames.Add(); ; } //生成的壓縮文件爲test.zip using (FileStream fsOut = System.IO.File.Create(Server.MapPath(zipFilePath+".zip"))) { //ZipOutputStream類的構造函數須要一個流,文件流、內存流均可以,壓縮後的內容會寫入到這個流中。 using (ZipOutputStream zipStream = new ZipOutputStream(fsOut)) { foreach (string file in filenames) { FileInfo fi = new FileInfo(file); string entryName = System.IO.Path.GetFileName(file); //ZipEntry類表明了一個壓縮包中的一個項,能夠是一個文件,也能夠是一個目錄。 ZipEntry newEntry = new ZipEntry(entryName); newEntry.DateTime = fi.LastWriteTime; newEntry.Size = fi.Length; //把壓縮項的信息添加到ZipOutputStream中。 zipStream.PutNextEntry(newEntry); byte[] buffer = new byte[4096]; //把須要壓縮文件以文件流的方式複製到ZipOutputStream中。 using (FileStream streamReader = System.IO.File.OpenRead(file)) { StreamUtils.Copy(streamReader, zipStream, buffer); } zipStream.CloseEntry(); } //使用流操做時必定要設置IsStreamOwner爲false。不然很容易發生在文件流關閉後的異常。 zipStream.IsStreamOwner = false; zipStream.Finish(); zipStream.Close(); } } // filenames = Directory.GetFiles(filesPath); //using (ZipOutputStream s = new ZipOutputStream(System.IO.File.Create(zipFilePath))) //{ // s.SetLevel(9); // 壓縮級別 0-9 // //s.Password = "123"; //Zip壓縮文件密碼 // byte[] buffer = new byte[4096]; //緩衝區大小 // foreach (string file in filenames) // { // ZipEntry entry = new ZipEntry(Path.GetFileName(file)); // entry.DateTime = DateTime.Now; // s.PutNextEntry(entry); // using (FileStream fs = System.IO.File.OpenRead(file)) // { // int sourceBytes; // do // { // sourceBytes = fs.Read(buffer, 0, buffer.Length); // s.Write(buffer, 0, sourceBytes); // } while (sourceBytes > 0); // } // } // s.Finish(); // s.Close(); //} } catch (Exception ex) { Console.WriteLine("Exception during processing {0}", ex); } return File(Server.MapPath(zipFilePath), "application/zip", "免冠照片.zip"); }