压缩文件的使用
程序员文章站
2022-04-08 23:41:04
首先引入dll文件ICSharpCode.SharpZipLib.dll 管理NuGet包里面下载 压缩文件 文件下载 具体使用 ......
首先引入dll文件icsharpcode.sharpziplib.dll 管理nuget包里面下载
压缩文件
1 /// <summary> 2 /// 压缩文件 3 /// </summary> 4 /// <param name="filename">要压缩的所有文件(完全路径)</param> 5 /// <param name="filename">文件名称</param> 6 /// <param name="name">压缩后文件路径</param> 7 /// <param name="level">压缩级别</param> 8 public void zipfilemain(string[] filenames, string[] filename, string name, int level) 9 { 10 zipoutputstream s = new zipoutputstream(file.create(name)); 11 crc32 crc = new crc32(); 12 //压缩级别 13 s.setlevel(level); // 0 - store only to 9 - means best compression 14 try 15 { 16 int m = 0; 17 foreach (string file in filenames) 18 { 19 //打开压缩文件 20 filestream fs = file.openread(file);//文件地址 21 byte[] buffer = new byte[fs.length]; 22 fs.read(buffer, 0, buffer.length); 23 //建立压缩实体 24 zipentry entry = new zipentry(filename[m].tostring());//原文件名 25 //时间 26 entry.datetime = datetime.now; 27 //空间大小 28 entry.size = fs.length; 29 fs.close(); 30 crc.reset(); 31 crc.update(buffer); 32 entry.crc = crc.value; 33 s.putnextentry(entry); 34 s.write(buffer, 0, buffer.length); 35 m++; 36 } 37 } 38 catch 39 { 40 throw; 41 } 42 finally 43 { 44 s.finish(); 45 s.close(); 46 } 47 }
文件下载
1 //下载打包文件 2 private void downloadfile(string filename, string filepath) 3 { 4 fileinfo fileinfo = new fileinfo(filepath); 5 response.clear(); 6 response.clearcontent(); 7 response.clearheaders(); 8 response.addheader("content-disposition", "attachment;filename=" + filename); 9 response.addheader("content-length", fileinfo.length.tostring()); 10 response.addheader("content-transfer-encoding", "binary"); 11 response.contenttype = "application/octet-stream"; 12 response.contentencoding = system.text.encoding.getencoding("gb2312"); 13 response.writefile(fileinfo.fullname); 14 response.flush(); 15 file.delete(filepath);//删除已下载文件 16 response.end(); 17 }
具体使用
1 protected void btndownloadfiles_click(object sender, eventargs e) 2 { 3 list<string> listfj = new list<string>();//保存附件路径 4 list<string> listfjname = new list<string>();//保存附件名字 5 for (int i = 0; i < gridview.rows.count; i++) 6 { 7 htmlinputcheckbox chk = (page.master.findcontrol("contentplaceholder1").findcontrol("gridview") as gridview).rows[i].findcontrol("checkboxname") as htmlinputcheckbox; 8 if (chk != null && chk.checked) 9 { 10 string temp = gridview.rows[i].cells[14].text.tostring().trim(); 11 if (temp != " ") 12 { 13 listfj.add(server.mappath("~") + temp); 14 listfjname.add(temp); 15 } 16 } 17 } 18 string time = datetime.now.ticks.tostring(); 19 zipfilemain(listfj.toarray(), listfjname.toarray(), server.mappath("~/uploadfiles/" + time + ".zip"), 9);//压缩文件 20 downloadfile(server.urlencode("附件.zip"), server.mappath("~/uploadfiles/" + time + ".zip"));//下载文件 21 }
上一篇: 从TXT文本文档向Sql Server中批量导入数据
下一篇: 虽然回家了但还是要过的有品位