1 /// <summary> 2 /// 指定路徑打包下載 3 /// </summary> 4 /// <param name="fileName"></param> 5 /// <param name="filePath"></param> 6 public void ZIPfiles(DataTable dt) 7 { 8 9 //string filename = "開店日期(正常).xlsx"; 10 //string filepath = "C:/ExportFolder/CADD87B4EDBE28A47669673F53DEC8458A998D5B84EEAA88EE6647CA6DF1D1E8.xlsx"; 11 string ZipName = string.Empty; 12 MemoryStream ms = new MemoryStream(); 13 Encoding gb2312 = Encoding.GetEncoding("gb2312"); //對方英文服務器 進行轉碼 14 ICSharpCode.SharpZipLib.Zip.ZipConstants.DefaultCodePage = gb2312.CodePage;//上面和這一句是爲了防止真是壞境是英文服務器出現中文亂碼的問題。 15 ZipOutputStream zos = new ZipOutputStream(ms); 16 FileStream fs = null; 17 // byte[] buffer = null; 18 System.IO.BinaryReader br = null; 19 20 try 21 { 22 if (dt.Rows.Count > 0) 23 { 24 //防止名稱重複 這一段確定是有點消耗性能的 暫時沒有找出更好的方法改進。 請各位大神有好的意見 說一下。 25 for (int i = dt.Rows.Count - 2; i > 0; i--) 26 { 27 int a = 0; 28 string title = dt.Rows[0]["fileName"].ToString(); 29 Logger.Log.Debug(title); 30 for (int j = i + 1; j > 0; j--) 31 { 32 if (dt.Rows[j]["fileName"].ToString() == title) 33 { 34 a++; 35 dt.Rows[j]["fileName"] = title + "("+a+")"; 36 37 } 38 Logger.Log.Debug(dt.Rows[j]["fileName"]); 39 } 40 41 } 42 43 foreach (DataRow dr in dt.Rows) 44 { 45 Logger.Log.Debug(dr["filePath"].ToString()); 46 fs = new FileStream(dr["filePath"].ToString(), System.IO.FileMode.Open);//文件地址、 47 // fs = new FileStream(filepath, System.IO.FileMode.Open);//文件地址 48 br = new BinaryReader((Stream)fs); 49 byte[] buffer = br.ReadBytes((Int32)fs.Length); 50 ZipEntry entry = new ZipEntry(dr["fileName"].ToString());//文件名 51 //ZipEntry entry = new ZipEntry(filename);//文件名 52 zos.PutNextEntry(entry);//UTF-8 53 zos.Write(buffer, 0, buffer.Length); 54 fs.Close(); //每個文件打開以後 而後執行完就必須在循環中關閉, 不然就會出現進程衝突 55 } 56 ZipName = DateTime.Now.ToString("yyyyMMdd"); 57 Logger.Log.Debug(ZipName); 58 } 59 } 60 catch (Exception ex) 61 { 62 Logger.Log.Error("ZIP打包錯誤" + ex); 63 throw (ex); 64 } 65 66 zos.Close(); 67 68 HttpContext.Current.Response.ContentType = "application/octet-stream"; 69 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(ZipName + ".zip", System.Text.Encoding.UTF8)); 70 HttpContext.Current.Response.AddHeader("Content-Length", ms.ToArray().Length.ToString()); 71 HttpContext.Current.Response.BinaryWrite(ms.ToArray()); 72 HttpContext.Current.Response.Flush(); 73 HttpContext.Current.Response.End(); 74 }