分享一个ASP.NET 文件压缩解压类 C#
需要引用一个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
- }
- }
分享一个ASP.NET 文件压缩解压类 C#的更多相关文章
- Linux 之 文件压缩解压
文件压缩解压 参考教程:[千峰教育] 命令: gzip: 作用:压缩文件,只能是单个文件,不能是多个,也不能是目录. 格式:gzip file 说明:执行命令会生成file.gz,删除原来的file ...
- linux驱动系列之文件压缩解压小节(转)
转至网页:http://www.jb51.net/LINUXjishu/43356.html Linux下最常用的打包程序就是tar了,使用tar程序打出来的包我们常称为tar包,tar包文件的命令通 ...
- iOS - File Archive/UnArchive 文件压缩/解压
1.ZipArchive 方式 ZipArchive 只能对 zip 类文件进行压缩和解压缩 GitHub 网址:https://github.com/ZipArchive/ZipArchive Zi ...
- linux文件压缩解压命令
01-.tar格式解包:[*******]$ tar xvf FileName.tar打包:[*******]$ tar cvf FileName.tar DirName(注:tar是打包,不是压缩! ...
- Linux基础------文件打包解包---tar命令,文件压缩解压---命令gzip,vim编辑器创建和编辑正文件,磁盘分区/格式化,软/硬链接
作业一:1) 将用户信息数据库文件和组信息数据库文件纵向合并为一个文件/1.txt(覆盖) cat /etc/passwd /etc/group > /1.txt2) 将用户信息数据库文件和用户 ...
- linux命令:压缩解压命令
压缩解压命令:gzip 命令名称:gzip 命令英文原意:GNU zip 命令所在路径:/bin/gzip 执行权限:所有用户 语法:gzip 选项 [文件] 功能描述:压缩文件 压缩后文件格式:g ...
- 基于哈夫曼编码的压缩解压程序(C 语言)
这个程序是研一上学期的课程大作业.当时,跨专业的我只有一点 C 语言和数据结构基础,为此,我查阅了不少资料,再加上自己的思考和分析,实现后不断调试.测试和完善,耗时一周左右,在 2012/11/19 ...
- linux笔记:linux常用命令-压缩解压命令
压缩解压命令:gzip(压缩文件,不保留原文件.这个命令不能压缩目录) 压缩解压命令:gunzip(解压.gz的压缩文件) 压缩解压命令:tar(打包压缩目录或者解压压缩文件.打包的意思是把目录打包成 ...
- c#自带压缩类实现的多文件压缩和解压
用c#自带的System.IO.Compression命名空间下的压缩类实现的多文件压缩和解压功能,缺点是多文件压缩包的解压只能调用自身的解压方法,和现有的压缩软件不兼容.下面的代码没有把多文件的目录 ...
随机推荐
- hibernate spring annotation setup
First step setup for the pom.xml with hibernate dependency , hibernate dependency need to before the ...
- 基于JQuery.timer插件实现一个计时器
基于JQuery.timer插件实现一个计时器,需要的朋友可以参考下. 先去官网下载jQuery Timers插件 ,然后引用到html中.这里是1.2 version 复制代码代码如下: < ...
- 面包板入门电子制作(class1)视频 全套30集高清
面包板入门电子制作(class1)套件(30集高清) 本套件以电子制作中最基础的元器件在面包板上搭建电路,用启发性的视频教学方式,使学习者熟悉电子电路基础.发挥想像力.在创新设计和制作中学会独立设计和 ...
- Android 使用java.net.socket 的接收问题
// 初始化socketsocket = new Socket(InetAddress.getByName(sip), sport);InputStream sin = socket.getInput ...
- eclipse maven 创建总POM 工程
首先进入到eclipse的workspace,我这里的workspace目录是D:\workspace 1.创建总的POM D:\workspace>mvn archetype:create - ...
- 数据标准化 Normalization
数据的标准化(normalization)是将数据按比例缩放,使之落入一个小的特定区间.在某些比较和评价的指标处理中经常会用到,去除数据的单位限制,将其转化为无量纲的纯数值,便于不同单位或量级的指标能 ...
- 统一回复《怎么学JavaScript?》
作者:小不了链接:https://zhuanlan.zhihu.com/p/23265155来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 鉴于时不时,有同学私信问我( ...
- 聊聊CSS postproccessors
阿里妈妈 @一丝 准备发布其CSSGrace,即CSS后处理插件,于是顺便聊聊CSS postprocessors. 从Rework说起 Rework是TJ大神开发的CSS预处理框架.但为什么会出 ...
- spring之ControllerAdvice注解
@ControllerAdvice是Spring 3.2新增的注解,主要是用来Controller的一些公共的需求的低侵入性增强提供辅助,作用于@RequestMapping标注的方法上. Contr ...
- How to set colors of HTML tables
There is a simple way to set the color of tables: use the bgcolor attribute of tag <table>. ...