上班第二天下班,课外作业,实现一个ZIP压缩的工具类.本来想用Package,但是写完了才发现不能解压其他工具压缩的zip包,比较麻烦,因此本工具类依赖了第三方的库(SharpZipLib  version 0.86.0 http://icsharpcode.github.io/SharpZipLib/),上午花了两个小时整理了下代码,mark下!

  

 /**
* Class: ZIP压缩工具类
* Reference: SharpZipLib version 0.86.0 (http://icsharpcode.github.io/SharpZipLib/)
* Author: Zengyq
* Version: 1.0
* Create Date: 2014-05-13
* Modified Date: 2014-05-14
*/ /****************构造函数*************************/
ZipUtils()
ZipUtils(int compressionLevel) /****************方法列表*************************/
/// <summary>
/// 功能: ZIP方式压缩文件(压缩目录)
/// </summary>
/// <param name="dirPath">被压缩的文件夹夹路径</param>
/// <param name="zipFilePath">生成压缩文件的路径,缺省值:文件夹名+.zip</param>
/// <param name="msg">返回消息</param>
/// <returns>是否压缩成功</returns>
public bool ZipFolder(string dirPath, string zipFilePath, out string msg) /// <summary>
/// 功能:压缩文件指定文件
/// </summary>
/// <param name="filenames">要压缩文件的绝对路径</param>
/// <param name="zipFilePath">生成压缩文件的路径, 缺省值为随机数字串.zip</param>
/// <param name="msg">返回消息</param>
/// <returns>是否压缩成功</returns>
public bool ZipFiles(string[] filenames, string zipFilePath, out string msg) /// <summary>
/// 解压ZIP格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,缺省值压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <param name="msg">返回消息</param>
/// <returns>解压是否成功</returns>
public bool UnZipFile(string zipFilePath, string unZipDir, out string msg) /// <summary>
/// 解压指定ZIP文件到当前路径
/// </summary>
/// <param name="zipFilePath">ZIP文件绝对路径</param>
/// <param name="msg">返回消息</param>
/// <returns>解压是否成功</returns>
public bool UnZipFileToCurrentPath(string zipFilePath, out string msg) /****************调用样例*************************/
ZipUtils zu = new ZipUtils();
string msg = "";
zu.UnZipFileToCurrentPath(@"C:\Users\zengyiqun\Desktop\package1024.zip", out msg);

  类实现,没有采用静态类的形式,看了某博客用了out作为msg不懂会不会用到,先这样了,以下是实现类:

 /**
* Class: ZIP压缩工具类
* Reference: SharpZipLib version 0.86.0 (http://icsharpcode.github.io/SharpZipLib/)
* Author: Zengyq
* Version: 1.0
* Create Date: 2014-05-13
* Modified Date: 2014-05-14
*/ using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO; public class ZipUtils
{
//缓存大小
private int BufferSize; //压缩率 0(无压缩)-9(压缩率最高)
private int CompressionLevel; //压缩是用于存放压缩路径
private string CompressPath; #region 构造函数
/// <summary>
/// 无参构造
/// </summary>
public ZipUtils()
{
this.BufferSize = ;
this.CompressionLevel = ;
} /// <summary>
/// 带参数构造
/// </summary>
/// <param name="compressionLevel">0(无压缩)-9(压缩率最高)</param>
public ZipUtils(int compressionLevel)
{
this.BufferSize = ;
this.CompressionLevel = compressionLevel;
}
#endregion #region 压缩方法
/// <summary>
/// 功能: ZIP方式压缩文件(压缩目录)
/// </summary>
/// <param name="dirPath">被压缩的文件夹夹路径</param>
/// <param name="zipFilePath">生成压缩文件的路径,缺省值:文件夹名+.zip</param>
/// <param name="msg">返回消息</param>
/// <returns>是否压缩成功</returns>
public bool ZipFolder(string dirPath, string zipFilePath, out string msg)
{
this.CompressPath = dirPath;
//判断目录是否为空
if (dirPath == string.Empty)
{
msg = "The Folder is empty";
return false;
} //判断目录是否存在
if (!Directory.Exists(dirPath))
{
msg = "The Folder is not exists";
return false;
} //压缩文件名为空时使用 文件夹名.zip
if (zipFilePath == string.Empty || zipFilePath == null)
{
if (dirPath.EndsWith("//"))
{
dirPath = dirPath.Substring(, dirPath.Length - );
}
zipFilePath = dirPath + ".zip";
} try
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(this.CompressionLevel);
ZipDirectory(dirPath, s);//压缩目录,包含子目录
s.Finish();
s.Close();
}
}
catch (Exception ex)
{
msg = ex.Message;
return false;
} msg = "Success";
return true;
}//end function /// <summary>
/// 压缩文件指定文件
/// </summary>
/// <param name="filenames">要压缩文件的绝对路径</param>
/// <param name="zipFilePath">生成压缩文件的路径, 缺省值为当前时间.zip</param>
/// <param name="msg">返回消息</param>
/// <returns>是否压缩成功</returns>
public bool ZipFiles(string[] filenames, string zipFilePath, out string msg)
{
msg = "";
if (filenames.Length == )
{
msg = "No File Selected";
return false;
} //压缩文件名为空时使用 文件夹名.zip
if (zipFilePath == string.Empty || zipFilePath == null)
{
zipFilePath = System.Environment.CurrentDirectory + "\\" + DateTime.Now.ToFileTimeUtc().ToString() + ".zip";
} try
{
using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
{
s.SetLevel(this.CompressionLevel);
ZipFilesAndDirectory(filenames,s);
s.Finish();
s.Close();
}//end using
}
catch (Exception ex)
{
msg = ex.Message;
return false;
} msg = "Success";
return true;
} #endregion #region 解压方法
/// <summary>
/// 解压ZIP格式的文件。
/// </summary>
/// <param name="zipFilePath">压缩文件路径</param>
/// <param name="unZipDir">解压文件存放路径,缺省值压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
/// <param name="msg">返回消息</param>
/// <returns>解压是否成功</returns>
public bool UnZipFile(string zipFilePath, string unZipDir, out string msg)
{
msg = ""; //判读路径是否为空
if (zipFilePath == string.Empty || zipFilePath == null)
{
msg = "ZipFile No Selected";
return false;
} //判读文件是否存在
if (!File.Exists(zipFilePath))
{
msg = "ZipFile No Exists";
return false;
}
//解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
if (unZipDir == string.Empty || unZipDir == null)
{
unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
} if (!unZipDir.EndsWith("//"))
{
unZipDir += "//";
} if (!Directory.Exists(unZipDir))
{
Directory.CreateDirectory(unZipDir);
} try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{ ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName.Length > )
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (!directoryName.EndsWith("//"))
{
directoryName += "//";
}
if (fileName != String.Empty && fileName != null)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
CopyStream(s, streamWriter);
}
}
}//end while
}//end using
}
catch (Exception ex)
{
msg = ex.Message;
return false;
} msg = "UnZip Success ! ";
return true;
}//end function /// <summary>
/// 解压指定ZIP文件到当前路径
/// </summary>
/// <param name="zipFilePath">ZIP文件绝对路径</param>
/// <param name="msg">返回消息</param>
/// <returns>解压是否成功</returns>
public bool UnZipFileToCurrentPath(string zipFilePath, out string msg)
{
msg = ""; //判读路径是否为空
if (zipFilePath == string.Empty || zipFilePath == null)
{
msg = "ZipFile No Selected";
return false;
} //判读文件是否存在
if (!File.Exists(zipFilePath))
{
msg = "ZipFile No Exists";
return false;
}
//解压到当前目录
string unZipDir = zipFilePath.Substring(, zipFilePath.LastIndexOf(@"\")); if (!unZipDir.EndsWith("//"))
{
unZipDir += "//";
} if (!Directory.Exists(unZipDir))
{
Directory.CreateDirectory(unZipDir);
} try
{
using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
{
ZipEntry theEntry;
while ((theEntry = s.GetNextEntry()) != null)
{
string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);
if (directoryName.Length > )
{
Directory.CreateDirectory(unZipDir + directoryName);
}
if (!directoryName.EndsWith("//"))
{
directoryName += "//";
}
if (fileName != String.Empty && fileName != null)
{
using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))
{
CopyStream(s, streamWriter);
}
}
}//end while
}//end using
}
catch (Exception ex)
{
msg = ex.Message;
return false;
} msg = "UnZip Success ! ";
return true;
}//end function #endregion #region 内部方法 /// <summary>
/// 内部类:递归压缩目录
/// </summary>
/// <param name="dirPath"></param>
/// <param name="s"></param>
private void ZipDirectory(string dirPath, ZipOutputStream s)
{
string[] filenames = Directory.GetFiles(dirPath);
byte[] buffer = new byte[this.BufferSize];
foreach (string file in filenames)
{
//处理相对路径问题
ZipEntry entry = new ZipEntry(file.Replace(this.CompressPath + "\\", String.Empty));
//设置压缩时间
entry.DateTime = DateTime.Now; s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
CopyStream(fs, s);
}
} //递归处理子目录
DirectoryInfo di = new DirectoryInfo(dirPath);
foreach (DirectoryInfo subDi in di.GetDirectories())
{
ZipDirectory(subDi.FullName, s);
} }//end function /// <summary>
///
/// </summary>
/// <param name="filenames"></param>
/// <param name="s"></param>
private void ZipFilesAndDirectory(string[] filenames, ZipOutputStream s)
{
byte[] buffer = new byte[this.BufferSize];
foreach (string file in filenames)
{
//当时文件的时候
if (System.IO.File.Exists(file))
{
ZipEntry entry = new ZipEntry(Path.GetFileName(file));
entry.DateTime = DateTime.Now;
s.PutNextEntry(entry);
using (FileStream fs = File.OpenRead(file))
{
CopyStream(fs, s);
}
} //当时目录的时候
if(System.IO.Directory.Exists(file))
{
this.CompressPath = file.Replace("\\" + Path.GetFileName(file),String.Empty);
ZipDirectory(file, s);
} } } /// <summary>
/// 按块复制
/// </summary>
/// <param name="source">源Stream</param>
/// <param name="target">目标Stream</param>
private void CopyStream(Stream source, Stream target)
{
byte[] buf = new byte[this.BufferSize];
int byteRead = ;
while ((byteRead = source.Read(buf, , this.BufferSize)) > )
{
target.Write(buf, , byteRead);
} }
#endregion }//end class

  代码风格还请大家轻喷,在.net程序员面前是个非主流java程序员,在java程序员面前是个非主流.net程序员。将以上工具类封装成了dll可以直接引用。

  附件:ZipUtils.rar

1 ZipUtils.rar
2 -src
3 -ZipUtils.cs
4 -dll
5 -SharpZipLib.dll
6 -ZipUtilsLib.dll

【C#】依赖于SharpZipLib的Zip压缩工具类的更多相关文章

  1. 最近工作用到压缩,写一个zip压缩工具类

    package test; import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream ...

  2. zip压缩工具类

    java将有关zip压缩的内容都封装在java.util.zip宝中,用java实现zip压缩,不用考虑压缩算法,java已经将这些进行了封装 实际上用java实现zip压缩涉及的就是一个“输入输出流 ...

  3. 压缩工具类 - ZipUtils.java

    压缩工具类,提供压缩文件.解压文件的方法. 源码如下:(点击下载 - ZipUtils.java .FolderUtils.java.ant-1.7.0.jar.commons-io-2.4.jar. ...

  4. Java 实现文件压缩工具类

    package com.wdxc.util; import java.io.BufferedInputStream; import java.io.File; import java.io.FileI ...

  5. php ZIP压缩类实例分享

    php ZIP压缩类实例分享 <?php $zipfiles =array("/root/pooy/test1.txt","/root/pooy/test2.txt ...

  6. zip压缩工具 tar打包 打包并压缩

    6.5 zip压缩工具 6.6 tar打包 6.7 打包并压缩 zip压缩工具 xz,bzip2,gzip都不支持压缩目录 zip可以压缩目录 压缩文件 zip  2.txt.zip  2.txt [ ...

  7. zip压缩工具,unzip解压缩工具

    zip压缩工具,unzip解压缩工具=================== [root@aminglinux tmp]# yum install -y zip[root@aminglinux tmp] ...

  8. Zip压缩工具、tar打包、打包并压缩

    第5周第2次课(4月17日) 课程内容: 6.5 zip压缩工具6.6 tar打包6.7 打包并压缩 6.5 zip压缩工具 Zip压缩工具最大的特点就是可以支持压缩目录,也能够压缩文件,Window ...

  9. Resource注解无法导入依赖使用javax.annotation的注解类

    Resource注解无法导入依赖使用javax.annotation的注解类 使用javax.annotation的注解类 javax.annotation.Resource 注解在eclipse中无 ...

随机推荐

  1. storm的并发和消息保障性

    Storm并发配置的优先级: defaults.yaml < storm.yaml < topology-specific configuration < internal  com ...

  2. java截取日期范围并计算相差月数

    前两天,媳妇单位让整理excel的某一个单元格内两个日期范围的相差月数,本人对excel操作不是很熟练,便写了个小程序计算了一下,原始需求如下: 计算投资期限的范围,并得到期限范围的相差月数 思路1: ...

  3. UVA 12380 Glimmr in Distress --DFS

    题意:给你一串数字序列,只包含0,1,2,一路扫描过去,遇到2则新开一个2x2的矩阵,然后如果扫到0或1就将其填入矩阵,注意不能四个方格全是0或者全是1,那样跟一个方格没区别,所以21111这种是不可 ...

  4. AutoIT简介

    AutoIT最初是为了帮助IT管理和维护而开发的工具,能自动完成软件的安装.由于自动化安装和自动化测试在功能需求上有许多相似之处,都要模拟用户对软件进行操作,并验证执行的结果,所以,AutoIT逐渐成 ...

  5. vue中如何不通过路由直接获取url中的参数

    前言:为什么要不通过路由直接获取url中的参数? vue中使用路由的方式设置url参数,但是这种方式必须要在路径中附带参数,而且这个参数是需要在vue的路由中提前设置好的. 相对来说,在某些情况下直接 ...

  6. fireworks将图片变为透明色

    如果是新建的图片,只要把画布背景设置成透明,图片完成后保存为GIF格式即可: 如果是已经存在的图片,用Fireworks将图片打开,然后按Ctrl+Shift+X,在弹出界面中格式选择为GIF.在右边 ...

  7. MahApps.Metro怎么调用消息窗口

    网上查看了好多资料,没有找到很清楚明了的结果,经过了多天的研究,无意发现了这个方法来进行全局调用 效果展示:

  8. 加密算法使用(一):用CRC32来压缩32uuid字符串

    CRC32相比MD5重复率较高, 不过我们仍然可以使用CRC32然后转长整形的方式将32位的UUID字符串压缩成更短的整形唯一标识. /** * * @Title: getCRC32Value * @ ...

  9. 2016科幻惊悚《第五波》HD720P.中英双字

    导演: J·布莱克森编剧: 苏珊娜·格兰特 / 阿齐瓦·高斯曼 / 杰夫·皮克纳 / 瑞克·杨西主演: 科洛·莫瑞兹 / 尼克·罗宾森 / 朗·里维斯顿 / 玛姬·丝弗 / 亚历克斯·罗伊 / 更多. ...

  10. MANIFEST.INF!JAR规范中

    MANIFEST.INF!JAR规范中 META-INF 目录中内容心得.顺带整理了网上资料,提供地址 标签: jarjava产品sunantapache 2012-03-31 17:09 2768人 ...