/// <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#压缩打包文件的更多相关文章

  1. java.util.zip压缩打包文件总结一:压缩文件及文件下面的文件夹

    一.简述 zip用于压缩和解压文件.使用到的类有:ZipEntry  ZipOutputStream 二.具体实现代码 package com.joyplus.test; import java.io ...

  2. asp.net C#压缩打包文件例子

    /// <summary> /// 压缩和解压文件 /// </summary> public class ZipClass { /// <summary> /// ...

  3. C#压缩打包文件

    该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册. 利用 SharpZipLib方便地压缩和解压缩文件最新版本的SharpZipLib(0.84)增加了很多新的功能,其中 ...

  4. java.util.zip压缩打包文件总结二: ZIP解压技术

    一.简述 解压技术和压缩技术正好相反,解压技术要用到的类:由ZipInputStream通过read方法对数据解压,同时需要通过CheckedInputStream设置冗余校验码,如: Checked ...

  5. SharePoint 压缩打包文件代码分享

    前言 最近碰到这样一个需求,用户需要批量打包下载sharepoint文档库中的文档,所以,就需要开发一个打包下载的服务. 然后,把打包的代码分享给大家,也许会有需要的人. static void Ma ...

  6. linux文件压缩与文件夹压缩(打包)

    目录 一:linux文件压缩 1.linux常见的压缩包有哪些? 2.bzip压缩(文件) 二:打包(文件夹压缩) 1.打包命令 2.参数 3.参数解析(实战) 4.注意事项 简介: win中的压缩包 ...

  7. C# 压缩打包文件下载

    C# 压缩打包文件下载 public class MyNameTransfom : ICSharpCode.SharpZipLib.Core.INameTransform { #region INam ...

  8. albert1017 Linux下压缩某个文件夹(文件夹打包)

    albert1017 Linux下压缩某个文件夹(文件夹打包) tar -zcvf /home/xahot.tar.gz /xahottar -zcvf 打包后生成的文件名全路径 要打包的目录例子:把 ...

  9. Linux中的文件压缩,打包和备份命令

    压缩解压命令 gzip  文件   -c : 将压缩数据输出到屏幕,可用来重定向 -v   显示压缩比等信息 -d   解压参数 -t    用来检验一个压缩文件的一致性看看档案有没错 -数字 : 压 ...

随机推荐

  1. 1.8 基础知识——GP2.7 识别和卷入干系人(Stakeholder) & GP2.9 质量保证(QA)

    GP2.7 识别和卷入干系人(Stakeholder) GP2.7 Identify and involve the relevant stakeholders of XXX process as p ...

  2. 创建用户故事地图(User Story Mapping)的8个步骤

    [小编]上周六了解了用户故事地图后,小编又查阅了一些资料,找到了以下这篇关于如何组织用户故事地图规划的文章,分享给大家.也希望大家如果有好的实践,也可以留言一起交流. 原文地址:http://winn ...

  3. 集群服务器 时间同步 - Chrony

    greenplum,openstack等云计算项目需要集群服务器部署,服务器之间的时间需要同步,但并不是所有机器可以 直接连外网,这时可以用Chrony工具解决. 解决方法是将其中一台设为时间服务器, ...

  4. mysql一些小技巧

    1 强制命中索引:force index 某些时候查询,索引会失效,可以进行强制命中索引 2 group_concat 能将相同的行组合起来. 当然,我推荐这种操作可以在代码中操作,如果必须在特定情况 ...

  5. 使用sql server profilter跟踪sql

    最近在研究EF延迟加载和贪婪加载的用法时,想要查看Linq生成的sql.一开始通过VS-->调试-->窗口-->IntelliTrace事件,来查看生成的sql,并不是十分准确.然后 ...

  6. CMPP3.0实现物联网卡通讯

    当下物联网发展迅猛,物联网卡可以接受短信指令,实现千里之外尽可掌控.本人做过一个这类项目,把相关经验记录下来,分享给需要的人. 物联网卡通讯其实跟电话卡一样,可以使用CMPP协议.不过由于物联网卡位数 ...

  7. Java高级编程之URL处理

    Java URL处理 URL(Uniform Resource Locator)中文名为统一资源定位符,有时也被俗称为网页地址.表示为互联网上的资源,如网页或者FTP地址. 本章节我们将介绍Java是 ...

  8. Servlet/JSP-06 Session

    一. 概述 Session 指客户端(浏览器)与服务器端之间保持状态的解决方案,有时候也用来指这种解决方案的存储结构. 当服务器端程序要为客户端的请求创建一个 Session 时,会首先检查这个请求里 ...

  9. ORA-01858: 在要求输入数字处找到非数字字符

    数据库   date  字段问题  insert into  WK_RE_LE  (DACL_FILE_ID,DACL_GROUP_ID,BDCDYH,DACL_LENGTH,ISVALID,DACL ...

  10. react native windows开发环境搭建(二)

    上一篇中介绍了本地服务器端环境的安装,使用已经编译好的apk程序,设置ip地址,就可以看到welcome界面,并且可以对程序做出修改以及调试. 为了扩展和发布应用 还需要能编译loader程序,这里介 ...