需要引用一个ICSharpCode.SharpZipLib.dll

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using System.Web;
namespace Mvc51Hiring.Common.Tool
{/// <summary>      /// 作者:来自网格    /// 修改人:sunkaixaun/// 压缩和解压文件  /// </summary>  public class ZipClass{/// <summary>  /// 所有文件缓存  /// </summary>  List<string> files = new List<string>();/// <summary>  /// 所有空目录缓存  /// </summary>  List<string> paths = new List<string>();/// <summary>  /// 压缩单个文件根据文件地址/// </summary>  /// <param name="fileToZip">要压缩的文件</param>  /// <param name="zipedFile">压缩后的文件全名</param>  /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  /// <param name="blockSize">分块大小</param>  public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize){if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错  {throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");}FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);FileStream zipFile = File.Create(zipedFile);ZipOutputStream zipStream = new ZipOutputStream(zipFile);ZipEntry zipEntry = new ZipEntry(fileToZip);zipStream.PutNextEntry(zipEntry);zipStream.SetLevel(compressionLevel);byte[] buffer = new byte[blockSize];int size = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, size);try{while (size < streamToZip.Length){int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, sizeRead);size += sizeRead;}}catch (Exception ex){GC.Collect();throw ex;}zipStream.Finish();zipStream.Close();streamToZip.Close();GC.Collect();}/// <summary>  /// 压缩目录(包括子目录及所有文件)  /// </summary>  /// <param name="rootPath">要压缩的根目录</param>  /// <param name="destinationPath">保存路径</param>  /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel){GetAllDirectories(rootPath);/* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾 { rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\" } *///string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。  string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。  Crc32 crc = new Crc32();ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression  foreach (string file in files){FileStream fileStream = File.OpenRead(file);//打开压缩文件  byte[] buffer = new byte[fileStream.Length];fileStream.Read(buffer, 0, buffer.Length);ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));entry.DateTime = DateTime.Now;// set Size and the crc, because the information  // about the size and crc should be stored in the header  // if it is not set it is automatically written in the footer.  // (in this case size == crc == -1 in the header)  // Some ZIP programs have problems with zip files that don't store  // the size and crc in the header.  entry.Size = fileStream.Length;fileStream.Close();crc.Reset();crc.Update(buffer);entry.Crc = crc.Value;outPutStream.PutNextEntry(entry);outPutStream.Write(buffer, 0, buffer.Length);}this.files.Clear();foreach (string emptyPath in paths){ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");outPutStream.PutNextEntry(entry);}this.paths.Clear();outPutStream.Finish();outPutStream.Close();GC.Collect();}/// <summary>  /// 多文件打包下载/// </summary>  public void DwonloadZip(string[] filePathList, string zipName){MemoryStream ms = new MemoryStream();byte[] buffer = null;var context = HttpContext.Current;using (ICSharpCode.SharpZipLib.Zip.ZipFile file = ICSharpCode.SharpZipLib.Zip.ZipFile.Create(ms)){file.BeginUpdate();file.NameTransform = new MyNameTransfom();//通过这个名称格式化器,可以将里面的文件名进行一些处理。默认情况下,会自动根据文件的路径在zip中创建有关的文件夹。foreach (var it in filePathList){file.Add(context.Server.MapPath(it));}file.CommitUpdate();buffer = new byte[ms.Length];ms.Position = 0;ms.Read(buffer, 0, buffer.Length);}context.Response.AddHeader("content-disposition", "attachment;filename=" + zipName);context.Response.BinaryWrite(buffer);context.Response.Flush();context.Response.End();}/// <summary>  /// 取得目录下所有文件及文件夹,分别存入files及paths  /// </summary>  /// <param name="rootPath">根目录</param>  private void GetAllDirectories(string rootPath){string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录  foreach (string path in subPaths){GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List  }string[] files = Directory.GetFiles(rootPath);foreach (string file in files){this.files.Add(file);//将当前目录中的所有文件全名存入文件List  }if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录  {this.paths.Add(rootPath);//记录空目录  }}/// <summary>  /// 解压缩文件(压缩文件中含有子目录)  /// </summary>  /// <param name="zipfilepath">待解压缩的文件路径</param>  /// <param name="unzippath">解压缩到指定目录</param>  /// <returns>解压后的文件列表</returns>  public List<string> UnZip(string zipfilepath, string unzippath){//解压出来的文件列表  List<string> unzipFiles = new List<string>();//检查输出目录是否以“\\”结尾  if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false){unzippath += "\\";}ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));ZipEntry theEntry;while ((theEntry = s.GetNextEntry()) != null){string directoryName = Path.GetDirectoryName(unzippath);string fileName = Path.GetFileName(theEntry.Name);//生成解压目录【用户解压到硬盘根目录时,不需要创建】  if (!string.IsNullOrEmpty(directoryName)){Directory.CreateDirectory(directoryName);}if (fileName != String.Empty){//如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入  if (theEntry.CompressedSize == 0)break;//解压文件到指定的目录  directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);//建立下面的目录和子目录  Directory.CreateDirectory(directoryName);//记录导出的文件  unzipFiles.Add(unzippath + theEntry.Name);FileStream streamWriter = File.Create(unzippath + theEntry.Name);int size = 2048;byte[] data = new byte[2048];while (true){size = s.Read(data, 0, data.Length);if (size > 0){streamWriter.Write(data, 0, size);}else{break;}}streamWriter.Close();}}s.Close();GC.Collect();return unzipFiles;}}public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform{#region INameTransform 成员public string TransformDirectory(string name){return null;}public string TransformFile(string name){return Path.GetFileName(name);}#endregion}
}

  

转载于:https://www.cnblogs.com/sunkaixuan/p/4943248.html

分享一个ASP.NET 文件压缩解压类 C#相关推荐

  1. python压缩文件tar_python 实现tar文件压缩解压的实例详解

    python 实现tar文件压缩解压的实例详解 python 实现tar文件压缩解压的实例详解 压缩文件: import tarfile import os def tar(fname): t = t ...

  2. Qt基于QuaZIP实现文件压缩/解压(Linux下)

    Qt基于QuaZIP实现文件压缩/解压(Linux下) 一.工具准备 二.编译zlib 1.下载zlib源码 2.配置 3.编译与安装 三.编译QuaZIP 1.下载QuaZIP源码 2.将zlib库 ...

  3. Qt基于QuaZIP实现文件压缩/解压(Win下)

    Qt基于QuaZIP实现文件压缩/解压(Win下) 一.工具准备 二.编译zlib 1.下载zlib源码 2.生成VS工程文件 3.使用VS进行编译 三.编译QuaZIP 1.下载QuaZIP源码 2 ...

  4. linux压缩文件恢复,Linux文件压缩解压命令

    Linux文件压缩解压命令QV7南京数据恢复-西数科技: 硬盘/手机/SSD数据恢复专家. 025-83608636 18913825606 tar功能:文件压缩解压QV7南京数据恢复-西数科技: 硬 ...

  5. Linux常用文件压缩/解压命令格式大全(tar、gzip、bzip2、zip、compress、cpio、compress、dd)建议收藏

    Linux常用文件压缩/解压命令格式大全 1. tar 2. gzip 3. bzip2 4. zip 5. compress 6. cpio 7.dd 1. tar 打包备份后的文件包缀:.tar ...

  6. linux jar和zip,Linux命令———zip和jar文件压缩解压

    Linux命令---zip和jar文件压缩解压 (1)ubuntu 使用unzip和zip压缩文件 1.功能作用:解压缩zip文件 2.位置:/usr/bin/unzip 3.格式用法:unzip [ ...

  7. 【文件压缩解压工具类-含密码】

    文件压缩解压工具类-含密码 一.zip4j简介 二.zip4j工具类使用步骤 1.添加maven依赖 2.工具类代码 3.调用测试 三.结语 一.zip4j简介 zip4j功能比较强大,支持加密.解密 ...

  8. Linux自学笔记 | 10 常用命令 - 压缩解压类

    Linux自学笔记 | 10 常用命令 - 压缩解压类 Linux自学笔记 | 01 文件系统和目录结构 Linux自学笔记 | 02 VIM编辑器的安装与使用 Linux自学笔记 | 03 Linu ...

  9. 【PC工具】文件压缩解压工具winrar解压缩装机必备软件,winRAR5.70免费无广告

    微信关注 "DLGG创客DIY" 设为"星标",重磅干货,第一时间送达. 今天分享一个常用的压缩解压工具winrar. 为啥要搞这个无广告版呢(废话),总之网上 ...

最新文章

  1. HDU - 6305 RMQ Similar Sequence(笛卡尔树)
  2. BeautifulSoup库的使用
  3. 台湾大学林轩田机器学习基石课程学习笔记6 -- Theory of Generalization
  4. 10个常用的Python图像处理工具,非常全了
  5. codesys 简单案例_第一章:初识Codesys-1.4从一个示例程序讲起
  6. 将Python脚本打包成可执行文件
  7. PHP简单实现单点登录功能示例
  8. 页面加载完毕执行多个JS函数
  9. 读书和不读书的女人之间,一眼就能看得出来差别
  10. 【JSON】FastJson 打印输格式化输出
  11. ip fragmentation_为什么 TCP/IP 协议会拆分数据
  12. Apache Commons Net 实现 FTP 上传/下载/删除/同步
  13. 华为hs8545m如何复位_在华为东莞松山湖基地,见证一场始于AI质检的智能制造变革...
  14. Qt制作年会抽奖一界面
  15. 电脑 chrome 浏览器下载视频插件推荐
  16. sxe增加服务器,sXe Injected服务端使用说明
  17. fftshift详解
  18. 欠采样临界采样matlab,信号临界采样、过采样、欠采样实验报告.doc
  19. 64位计算机装32位系统,32位装64位系统教程
  20. 30%自媒体从业者才知道的爆款标题的专用模板,封面图的文案同样适用。

热门文章

  1. 漫谈中国自主杀毒引擎
  2. 计算器软件----表达式求值
  3. OCP 042全真试题讲解
  4. KDEWin Installer 0.9.8-1发布
  5. Kettle日常使用汇总整理
  6. 表单验证自定义二选一
  7. PHP $_REQUEST获取表单提交的代码
  8. ++i和i++效率谁高
  9. [WPF Bug清单]之(6)——Button的IsCancel属性失效
  10. 【集训队作业2018】喂鸽子