1 protected void btn_Down(object sender, EventArgs e) 2 { 3 string filePath = Server.MapPath("/TradeLog/" + txtDate.Text.Trim()); 4 if (!downBeforeValidation(filePath)) 5 return; 6 dlZipDir(filePath, txtDate.Text); 7 } 8 9 ///10 /// 下载前验证11 /// 12 /// 文件路径13 ///14 private bool downBeforeValidation(string filePath)15 {16 //判断密码是否正确17 string downPassWord = WebConfigurationManager.AppSettings["downPassWord"];18 if (string.IsNullOrEmpty(txtPassWord.Text) || txtPassWord.Text.Trim() != downPassWord)19 {20 Response.Write("");21 return false;22 }23 //判断文件是否存在24 25 if (!Directory.Exists(filePath))26 {27 Response.Write("");28 return false;29 }30 return true;31 }32 33 /// 34 /// 全部变量35 /// 36 ZipOutputStream zos = null;37 String strBaseDir = "";38 ///39 /// 下载文件40 /// 41 /// 路径42 /// 下载后默认显示文件名称43 void dlZipDir(string strPath, string strFileName)44 {45 MemoryStream ms = null;46 Response.ContentType = "application/octet-stream";47 strFileName = HttpUtility.UrlEncode(strFileName).Replace('+', ' ');48 Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileName + ".zip");49 ms = new MemoryStream();50 zos = new ZipOutputStream(ms);51 strBaseDir = strPath + "\\";52 addZipEntry(strBaseDir);53 zos.Finish();54 zos.Close();55 Response.Clear();56 Response.BinaryWrite(ms.ToArray());57 Response.End();58 }59 60 ///61 /// 生成压缩文件62 /// 63 /// 64 void addZipEntry(string PathStr)65 {66 DirectoryInfo di = new DirectoryInfo(PathStr);67 foreach (DirectoryInfo item in di.GetDirectories())68 {69 addZipEntry(item.FullName);70 }71 foreach (FileInfo item in di.GetFiles())72 {73 FileStream fs = File.OpenRead(item.FullName);74 byte[] buffer = new byte[fs.Length];75 fs.Read(buffer, 0, buffer.Length);76 string strEntryName = item.FullName.Replace(strBaseDir, "");77 ZipEntry entry = new ZipEntry(strEntryName);78 zos.PutNextEntry(entry);79 zos.Write(buffer, 0, buffer.Length);80 fs.Close();81 }82 }