C#压缩打包文件
该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册。
利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。
压缩:
- /// <summary>
- /// 创建Zip对象
- /// </summary>
- /// <param name="filename">文件名.</param>
- /// <param name="directory">将要压缩的目录.</param>
- public static void ZipFile(string filename, string directory)
- {
- try
- {
- FastZip fz = new FastZip();
- fz.CreateEmptyDirectories = true;
- fz.CreateZip(filename, directory, true, "");
- fz = null;
- }
- catch (Exception)
- {
- throw;
- }
- }
解压缩:
- /// <summary>
- /// 解压缩.
- /// </summary>
- /// <param name="file">文件.</param>
- /// <returns>解压成功返回true,否则false</returns>
- public static bool UnpackFiles(string file, string dir)
- {
- try
- {
- if (!Directory.Exists(dir))
- Directory.CreateDirectory(dir);
- ZipInputStream s = new ZipInputStream(File.OpenRead(file));
- ZipEntry theEntry;
- while ((theEntry = s.GetNextEntry()) != null)
- {
- string directoryName = Path.GetDirectoryName(theEntry.Name);
- string fileName = Path.GetFileName(theEntry.Name);
- if (directoryName != String.Empty)
- Directory.CreateDirectory(dir + directoryName);
- if (fileName != String.Empty)
- {
- FileStream streamWriter = File.Create(dir + theEntry.Name);
- int size = ;
- byte[] data = new byte[];
- while (true)
- {
- size = s.Read(data, , data.Length);
- if (size > )
- {
- streamWriter.Write(data, , size);
- }
- else
- {
- break;
- }
- }
- streamWriter.Close();
- }
- }
- s.Close();
- return true;
- }
- catch (Exception)
- {
- throw;
- }
- }
以下是SharpZipLib的另一种方法,其中方法全:
- /// <summary>
- /// 压缩和解压文件
- /// </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, , buffer.Length);
- zipStream.Write(buffer, , size);
- try
- {
- while (size < streamToZip.Length)
- {
- int sizeRead = streamToZip.Read(buffer, , buffer.Length);
- zipStream.Write(buffer, , 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, , 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, , 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>
- /// 取得目录下所有文件及文件夹,分别存入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 == )//如果是空目录
- {
- 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 == )
- break;
- //解压文件到指定的目录
- directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
- //建立下面的目录和子目录
- Directory.CreateDirectory(directoryName);
- //记录导出的文件
- unzipFiles.Add(unzippath + theEntry.Name);
- FileStream streamWriter = File.Create(unzippath + theEntry.Name);
- int size = ;
- byte[] data = new byte[];
- while (true)
- {
- size = s.Read(data, , data.Length);
- if (size > )
- {
- streamWriter.Write(data, , size);
- }
- else
- {
- break;
- }
- }
- streamWriter.Close();
- }
- }
- s.Close();
- GC.Collect();
- return unzipFiles;
- }
- }
C#压缩打包文件的更多相关文章
- [转]C#压缩打包文件
/// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// ...
- java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹
一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...
- asp.net C#压缩打包文件例子
/// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// ...
- java.util.zip压缩打包文件总结二: ZIP解压技术
一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...
- SharePoint 压缩打包文件代码分享
前言 最近碰到这样一个需求,用户需要批量打包下载sharepoint文档库中的文档,所以,就需要开发一个打包下载的服务. 然后,把打包的代码分享给大家,也许会有需要的人. static void Ma ...
- linux文件压缩与文件夹压缩(打包)
目录 一:linux文件压缩 1.linux常见的压缩包有哪些? 2.bzip压缩(文件) 二:打包(文件夹压缩) 1.打包命令 2.参数 3.参数解析(实战) 4.注意事项 简介: win中的压缩包 ...
- C# 压缩打包文件下载
C# 压缩打包文件下载 public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform { #region INam ...
- albert1017 Linux下压缩某个文件夹(文件夹打包)
albert1017 Linux下压缩某个文件夹(文件夹打包) tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录例子:把 ...
- Linux中的文件压缩,打包和备份命令
压缩解压命令 gzip 文件 -c : 将压缩数据输出到屏幕,可用来重定向 -v 显示压缩比等信息 -d 解压参数 -t 用来检验一个压缩文件的一致性看看档案有没错 -数字 : 压 ...
随机推荐
- socket发送、接收信息----UDP
# 导入套接字包 import socket def welcome(): print("------欢迎进入UDP聊天器--------") print("1.发送信息 ...
- python中的lambda()函数
语句:print map(lambda x:x ** 2,[1,2,3,4,5]) 其中lambda()函数在Python文档,文档中解释如下: lambda An anonymous inline ...
- require sqlite3时报The specified module could not be found.错误
http://dependencywalker.com/ 在这个站点下载对应平台的Dependency Walker,打开你自己编译好的.node文件(sqlite3\lib\binding\node ...
- [bzoj 2693] jzptab & [bzoj 2154] Crash的数字表格 (莫比乌斯反演)
题目描述 TTT组数据,给出NNN,MMM,求∑x=1N∑y=1Mlim(x,y)\sum_{x=1}^N\sum_{y=1}^M lim(x,y)\newlinex=1∑Ny=1∑Mlim(x, ...
- 微信&QQ中打开网页提示“已停止访问该网页”是怎么回事?
背景 大家是不是经常会遇到这种情况,分享出去的网页链接在微信里或者QQ里打开会提示“已停止访问该网页”,当大家看到这种的提示的时候就说明你访问的网页已经被腾讯拦截了. 当大家遇到以上这种情况的时候要怎 ...
- HTML 003 元素
HTML 元素 HTML 文档由 HTML 元素定义. HTML 元素 开始标签 * 元素内容 结束标签 * <p> 这是一个段落 </p> <a href=" ...
- loj #2319
noip2017列队 - resolve 标签:题解 \(n * m\) 的矩阵,每个元素 \((i, j)\) 的标号为 \((i - 1) * m + j\), 每次给出 \((x, y)\), ...
- 01.Flink笔记-编译、部署
Flink开发环境部署配置 Flink是一个以Java及Scala作为开发语言的开源大数据项目,代码开源在github上,并使用maven来编译和构建项目.所需工具:Java.maven.Git. 本 ...
- ROS常用命令
ROS常用命令 打印ros环境变量 $ echo $ROS_PACKAGE_PATH 确认环境变量已经设置正确 export | grep ROS 环境变量设置文件 sudo gedit ./.bas ...
- SpringCloud介绍及入门一
springcloud是什么 基于spring boot实现的服务治理工具包,管理和协微服务 把别人的东西拿来组合在一起,形成各种组件 微服务协调者[service registtry注册中心 Eur ...