用ICSharpCode.SharpZipLib进行压缩

今天过中秋节,当地时间(2013-09-08),公司也放假了,正好也闲着没事,就在网上学习学习,找找资料什么的。
最近项目上可能会用到压缩的功能,所以自己就先在网上学习了,发现一个不错的用于压缩的DLL文件,并且免费,而且开放源码;
这就是我今天介绍的对象:

SharpZipLib

我们先看看它的官方介绍吧:

#ziplib (SharpZipLib, formerly NZipLib) is a Zip, GZip, Tar and BZip2 library written entirely in C# for the .NET platform. It is implemented as an assembly (installable in the GAC), and thus can easily be incorporated into other projects (in any .NET language). The creator of #ziplib put it this way: "I've ported the zip library over to C# because I needed gzip/zip compression and I didn't want to use libzip.dll or something like this. I want all in pure C#."

Download
  • Assemblies for .NET 1.1, .NET 2.0 (3.5, 4.0), .NET CF 1.0, .NET CF 2.0: Download 237 KB
  • Source code and samples Download 708 KB
  • Help file Download 1208 KB

All downloads are for version 0.86.0, built on 2010/05/25.

 

以上是从官方网站截取的部分说明,根据当前时间2014/09/08(中秋节),可以看到目前官方发布的版本号是0.86.0根据没有时间给大家报道。

这里下载:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
源代码:http://www.icsharpcode.net/OpenSource/SharpZipLib/DownloadLatestVersion.asp?what=sourcesamples
修改记录:http://wiki.sharpdevelop.net/default.aspx/SharpZipLib.ReleaseHistory
SharpZipLib的许可是经过修改的GPL,底线是允许用在不开源商业软件中,意思就是免费使用。

以上参考网站:http://unruledboy.cnblogs.com/archive/2005/08/05/SharpZipLib084.html

=======================================================================================

添加引用ICSharpCode.SharpZipLib.dll

using System;
using System.Collections.Generic;
using System.IO;
using System.Threading;
using ICSharpCode.SharpZipLib.Zip;
 
namespace Lib
{
    /// 
    /// 文件压缩、解压缩
    /// 
    public class FileCompression
    {
        /// 
        /// 构造函数
        /// 
        public FileCompression()
        {
        }
        #region 加密、压缩文件
        /// 
        /// 压缩文件
        /// 
        /// <param name="fileNames">要打包的文件列表
        /// <param name="GzipFileName">目标文件名
        /// <param name="CompressionLevel">压缩品质级别(0~9)
        /// <param name="SleepTimer">休眠时间(单位毫秒)     
        public static void Compress(List fileNames, string GzipFileName, int CompressionLevel, int SleepTimer)
        {
            ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));
            try
            {
                s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression
                foreach (FileInfo file in fileNames)
                {
                    FileStream fs = null;
                    try
                    {
                        fs = file.Open(FileMode.Open, FileAccess.ReadWrite);
                    }
                    catch
                    { continue; }                   
                    //  方法二,将文件分批读入缓冲区
                    byte[] data = new byte[2048];
                    int size = 2048;
                    ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));
                    entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);
                    s.PutNextEntry(entry);
                    while (true)
                    {
                        size = fs.Read(data, 0, size);
                        if (size <= 0) break;                       
                        s.Write(data, 0, size);
                    }
                    fs.Close();
                    file.Delete();
                    Thread.Sleep(SleepTimer);
                }
            }
            finally
            {
                s.Finish();
                s.Close();
            }
        }
        #endregion
        #region 解密、解压缩文件
        /// 
        /// 解压缩文件
        /// 
        /// <param name="GzipFile">压缩包文件名
        /// <param name="targetPath">解压缩目标路径       
        public static void Decompress(string GzipFile, string targetPath)
        { 
            //string directoryName = Path.GetDirectoryName(targetPath + "//") + "//";
            string directoryName = targetPath;
            if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录
            string CurrentDirectory = directoryName;
            byte[] data = new byte[2048];
            int size = 2048;
            ZipEntry theEntry = null;           
            using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))
            {
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.IsDirectory)
                    {// 该结点是目录
                        if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);
                    }
                    else
                    {
                        if (theEntry.Name != String.Empty)
                        {
                            //解压文件到指定的目录
                            using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))
                            {
                                while (true)
                                {
                                    size = s.Read(data, 0, data.Length);
                                    if (size <= 0) break;
                                    
                                    streamWriter.Write(data, 0, size);
                                }
                                streamWriter.Close();
                            }
                        }
                    }
                }
                s.Close();
            }           
        }
        #endregion
    }
}

以上参考出处: .Net 下利用ICSharpCode.SharpZipLib.dll实现文件压缩、解压缩

=======================================================================================

一、使用ICSharpCode.SharpZipLib.dll;  

  下载地址   http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx  

二、压缩算法介绍:
  基于(ICSharpCode.SharpZipLib.dll)的文件压缩方法,类文件

程序代码----压缩文件:

using System;
using System.IO;
using System.Collections;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;


namespace FileCompress
{
    /// <summary>
    /// 功能:压缩文件
    /// creator chaodongwang 2009-11-11
    /// </summary>
    public class ZipClass
    {
        /// <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)
        {
            //如果文件没有找到,则报错 
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("文件:" + FileToZip + "没有找到!");
            }

            if (ZipedFile == string.Empty)
            {
                ZipedFile = Path.GetFileNameWithoutExtension(FileToZip) + ".zip";
            }

            if (Path.GetExtension(ZipedFile) != ".zip")
            {
                ZipedFile = ZipedFile + ".zip";
            }

            ////如果指定位置目录不存在,创建该目录
            //string zipedDir = ZipedFile.Substring(0,ZipedFile.LastIndexOf("//"));
            //if (!Directory.Exists(zipedDir))
            //    Directory.CreateDirectory(zipedDir);

            //被压缩文件名称
            string filename = FileToZip.Substring(FileToZip.LastIndexOf('//') + 1);
            
            System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipEntry ZipEntry = new ZipEntry(filename);
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[2048];
            System.Int32 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 (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                ZipStream.Finish();
                ZipStream.Close();
                StreamToZip.Close();
            }
        }

        /// <summary>
        /// 压缩文件夹的方法
        /// </summary>
        public void ZipDir(string DirToZip, string ZipedFile, int CompressionLevel)
        {
            //压缩文件为空时默认与压缩文件夹同一级目录
            if (ZipedFile == string.Empty)
            {
                ZipedFile = DirToZip.Substring(DirToZip.LastIndexOf("//") + 1);
                ZipedFile = DirToZip.Substring(0, DirToZip.LastIndexOf("//")) +"//"+ ZipedFile+".zip";
            }

            if (Path.GetExtension(ZipedFile) != ".zip")
            {
                ZipedFile = ZipedFile + ".zip";
            }

            using (ZipOutputStream zipoutputstream = new ZipOutputStream(File.Create(ZipedFile)))
            {
                zipoutputstream.SetLevel(CompressionLevel);
                Crc32 crc = new Crc32();
                Hashtable fileList = getAllFies(DirToZip);
                foreach (DictionaryEntry item in fileList)
                {
                    FileStream fs = File.OpenRead(item.Key.ToString());
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ZipEntry entry = new ZipEntry(item.Key.ToString().Substring(DirToZip.Length + 1));
                    entry.DateTime = (DateTime)item.Value;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zipoutputstream.PutNextEntry(entry);
                    zipoutputstream.Write(buffer, 0, buffer.Length);
                }
            }
        }

        /// <summary>
        /// 获取所有文件
        /// </summary>
        /// <returns></returns>
        private Hashtable getAllFies(string dir)
        {
            Hashtable FilesList = new Hashtable();
            DirectoryInfo fileDire = new DirectoryInfo(dir);
            if (!fileDire.Exists)
            {
                throw new System.IO.FileNotFoundException("目录:" + fileDire.FullName + "没有找到!");
            }

            this.getAllDirFiles(fileDire, FilesList);
            this.getAllDirsFiles(fileDire.GetDirectories(), FilesList);
            return FilesList;
        }
        /// <summary>
        /// 获取一个文件夹下的所有文件夹里的文件
        /// </summary>
        /// <param name="dirs"></param>
        /// <param name="filesList"></param>
        private void getAllDirsFiles(DirectoryInfo[] dirs, Hashtable filesList)
        {
            foreach (DirectoryInfo dir in dirs)
            {
                foreach (FileInfo file in dir.GetFiles("*.*"))
                {
                    filesList.Add(file.FullName, file.LastWriteTime);
                }
                this.getAllDirsFiles(dir.GetDirectories(), filesList);
            }
        }
        /// <summary>
        /// 获取一个文件夹下的文件
        /// </summary>
        /// <param name="strDirName">目录名称</param>
        /// <param name="filesList">文件列表HastTable</param>
        private void getAllDirFiles(DirectoryInfo dir, Hashtable filesList)
        {
            foreach (FileInfo file in dir.GetFiles("*.*"))
            {
                filesList.Add(file.FullName, file.LastWriteTime);
            }
        }
    }
}

程序代码----解压文件

using System;
using System.Collections.Generic;
/// <summary> 
/// 解压文件 
/// </summary> 

using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams; 

namespace FileCompress
{
    /// <summary>
    /// 功能:解压文件
    /// creator chaodongwang 2009-11-11
    /// </summary>
    public class UnZipClass
    {
        /// <summary>
        /// 功能:解压zip格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <param name="err">出错信息</param>
        /// <returns>解压是否成功</returns>
        public void UnZip(string zipFilePath, string unZipDir)
        {
            if (zipFilePath == string.Empty)
            {
                throw new Exception("压缩文件不能为空!");
            }
            if (!File.Exists(zipFilePath))
            {
                throw new System.IO.FileNotFoundException("压缩文件不存在!");
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
            if (unZipDir == string.Empty)
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            if (!unZipDir.EndsWith("//"))
                unZipDir += "//";
            if (!Directory.Exists(unZipDir))
                Directory.CreateDirectory(unZipDir);

            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 > 0)
                    {
                        Directory.CreateDirectory(unZipDir + directoryName);
                    }
                    if (!directoryName.EndsWith("//"))
                        directoryName += "//";
                    if (fileName != String.Empty)
                    {
                        using (FileStream streamWriter = File.Create(unZipDir + 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;
                                }
                            }
                        }
                    }
                }
            }
        }
    } 
}

s.net(c#.net)实例下载 :/Files/chaodongwang/FileCompress.rar

转自:http://www.cnblogs.com/chaodongwang/archive/2009/11/11/1600821.html

出处参考:http://blog.csdn.net/paolei/article/details/5405423

=======================================================================================

     ZipLib组件与.net自带的Copression比较,在压缩方面更胜一筹,经过BZip2压缩要小很多,亲手测试,不信你也可以试一试。而且这个功能更加强大。下面就是个人做的一个小例子,具体的应用程序源码: /Files/yank/Compress.rar

using System;
using System.Data;
using System.IO;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;

/// <summary>
/// Summary description for ICSharp
/// </summary>
public class ICSharp
{
    public ICSharp()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    /// 压缩
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public string Compress(string param)
    {
        byte[] data = System.Text.Encoding.UTF8.GetBytes(param);
        //byte[] data = Convert.FromBase64String(param);
        MemoryStream ms = new MemoryStream();
        Stream stream = new ICSharpCode.SharpZipLib.BZip2.BZip2OutputStream(ms);
        try
        {
            stream.Write(data, 0, data.Length);
        }
        finally 
        {
            stream.Close();
            ms.Close();
        }
        return Convert.ToBase64String(ms.ToArray());
    }
    /// <summary>
    /// 解压
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public string Decompress(string param)
    {
        string commonString="";
        byte[] buffer=Convert.FromBase64String(param);
        MemoryStream ms = new MemoryStream(buffer);
        Stream sm = new ICSharpCode.SharpZipLib.BZip2.BZip2InputStream(ms);
        //这里要指明要读入的格式,要不就有乱码
        StreamReader reader = new StreamReader(sm,System.Text.Encoding.UTF8);
        try
        {
            commonString=reader.ReadToEnd();
        }
        finally
        {
            sm.Close();
            ms.Close();
        }
        return commonString;
    }
}

Encoding.UTF8与Convert.FromBase64String

Encoding.UTF8 属性
      获取 UTF-8 格式的编码。 
Unicode 标准为所有支持脚本中的每个字符分配一个码位(一个数字)。Unicode 转换格式 (UTF) 是一种码位编码方式。Unicode 标准 3.2 版使用下列 UTF: 
      UTF-8,它将每个码位表示为一个由 1 至 4 个字节组成的序列。
      UTF-16,它将每个码位表示为一个由 1 至 2 个 16 位整数组成的序列。
      UTF-32,它将每个码位表示为一个 32 位整数。

Convert.FromBase64String 方法
将指定的 String(它将二进制数据编码为 base 64 数字)转换成等效的 8 位无符号整数数组。 
它的参数也又一定的要求:

参数是 由基 64 数字、空白字符和尾随填充字符组成。从零开始以升序排列的以 64 为基的数字为大写字符“A”到“Z”、小写字符“a”到“z”、数字“0”到“9”以及符号“+”和“/”。空白字符为 Tab、空格、回车和换行。s 中可以出现任意数目的空白字符,因为所有空白字符都将被忽略。无值字符“=”用于尾部的空白。s 的末尾可以包含零个、一个或两个填充字符。
异常:

异常类型条件
ArgumentNullException s 为空引用(Visual Basic 中为 Nothing)。
FormatException s 的长度(忽略空白字符)小于 4。

- 或 -

s 的长度(忽略空白字符)不是 4 的偶数倍。

s 的长度(忽略空白字符)不是 4 的偶数倍。

 

出处:http://www.cnblogs.com/yank/archive/2007/11/21/967515.html

=======================================================================================

直接看代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib.Zip;

namespace GlobalsTech.ZP.Common
{
    public class ZIP
    {
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="FileToZip">要压缩的文件</param>
        /// <param name="ZipedFile">压缩之后的路径</param>
        /// <param name="Password">密码</param>
        /// <returns></returns>
        public static bool ZipFile(string FileToZip, string ZipedFile, String Password)
        {
            //如果文件没有找到,则报错
            if (!File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            }

            FileStream ZipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry ZipEntry = null;

            bool res = true;

            try
            {
                ZipFile = File.OpenRead(FileToZip);
                byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 0, buffer.Length);
                ZipFile.Close();

                ZipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(ZipFile);
                // ZipStream.Password = Password;
                ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(6);

                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }

                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }

                if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile = null;
                }

                GC.Collect();
                GC.Collect(1);
            }

            return res;
        }




        /// <summary>解压文件</summary>
        /// <param name="file">压缩文件的名称,如:C:\123\123.zip</param>
        /// <param name="dir">dir要解压的文件夹路径</param>
        /// <returns></returns>
        public static bool UnpackFiles(string file, string dir)
        {
            try
            {
                if (!File.Exists(file))
                    return false;

                dir = dir.Replace("/", "\\");
                if (!dir.EndsWith("\\"))
                    dir += "\\";

                if (!Directory.Exists(dir))
                    Directory.CreateDirectory(dir);

                ZipInputStream s = new ZipInputStream(File.OpenRead(file));
                //s.Password
                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 = 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();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

    }
}

 


出处:http://hi.baidu.com/xiaocai06/item/fce1b482b173e8dbd0f8cd65

=======================================================================================

C# 利用SharpZipLib生成压缩包

本文通过一个简单的小例子简述SharpZipLib压缩文件的常规用法,仅供学习分享使用,如有不足之处,还请指正。

什么是SharpZipLib ?

SharpZipLib是一个C#的类库,主要用来解压缩Zip,GZip,BZip2,Tar等格式,是以托管程序集的方式实现,可以方便的应用于其他的项目之中。

在工程中引用SharpZipLib

在项目中,点击项目名称右键-->管理NuGet程序包,打开NuGet包管理器窗口,进行搜索下载即可,如下图所示:

SharpZipLib的关键类结构图

如下所示:

涉及知识点:

  • ZipOutputStream 压缩输出流,将文件一个接一个的写入压缩文档,此类不是线程安全的。
  • PutNextEntry 开始一个新的ZIP条目,ZipOutputStream中的方法。
  • ZipEntry 一个ZIP文件中的条目,可以理解为压缩包里面的一个文件夹/文件。
  • ZipInputStream 解压缩输出流,从压缩包中一个接一个的读出文档。
  • GetNextEntry 读出ZIP条目,ZipInputStream中的方法。

示例效果图:

关于解压缩小例子的示例效果图,如下:

核心代码

  1 using ICSharpCode.SharpZipLib.Checksum;
  2 using ICSharpCode.SharpZipLib.Zip;
  3 using System;
  4 using System.Collections.Generic;
  5 using System.IO;
  6 using System.Linq;
  7 using System.Text;
  8 using System.Threading.Tasks;
  9 
 10 namespace DemoZip
 11 {
 12     class ZipHelper
 13     {
 14         private string rootPath = string.Empty;
 15 
 16         #region 压缩  
 17 
 18         /// <summary>   
 19         /// 递归压缩文件夹的内部方法   
 20         /// </summary>   
 21         /// <param name="folderToZip">要压缩的文件夹路径</param>   
 22         /// <param name="zipStream">压缩输出流</param>   
 23         /// <param name="parentFolderName">此文件夹的上级文件夹</param>   
 24         /// <returns></returns>   
 25         private  bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
 26         {
 27             bool result = true;
 28             string[] folders, files;
 29             ZipEntry ent = null;
 30             FileStream fs = null;
 31             Crc32 crc = new Crc32();
 32 
 33             try
 34             {
 35                 string entName = folderToZip.Replace(this.rootPath, string.Empty)+"/";
 36                 //Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")
 37                 ent = new ZipEntry(entName);
 38                 zipStream.PutNextEntry(ent);
 39                 zipStream.Flush();
 40 
 41                 files = Directory.GetFiles(folderToZip);
 42                 foreach (string file in files)
 43                 {
 44                     fs = File.OpenRead(file);
 45 
 46                     byte[] buffer = new byte[fs.Length];
 47                     fs.Read(buffer, 0, buffer.Length);
 48                     ent = new ZipEntry(entName + Path.GetFileName(file));
 49                     ent.DateTime = DateTime.Now;
 50                     ent.Size = fs.Length;
 51 
 52                     fs.Close();
 53 
 54                     crc.Reset();
 55                     crc.Update(buffer);
 56 
 57                     ent.Crc = crc.Value;
 58                     zipStream.PutNextEntry(ent);
 59                     zipStream.Write(buffer, 0, buffer.Length);
 60                 }
 61 
 62             }
 63             catch
 64             {
 65                 result = false;
 66             }
 67             finally
 68             {
 69                 if (fs != null)
 70                 {
 71                     fs.Close();
 72                     fs.Dispose();
 73                 }
 74                 if (ent != null)
 75                 {
 76                     ent = null;
 77                 }
 78                 GC.Collect();
 79                 GC.Collect(1);
 80             }
 81 
 82             folders = Directory.GetDirectories(folderToZip);
 83             foreach (string folder in folders)
 84                 if (!ZipDirectory(folder, zipStream, folderToZip))
 85                     return false;
 86 
 87             return result;
 88         }
 89 
 90         /// <summary>   
 91         /// 压缩文件夹    
 92         /// </summary>   
 93         /// <param name="folderToZip">要压缩的文件夹路径</param>   
 94         /// <param name="zipedFile">压缩文件完整路径</param>   
 95         /// <param name="password">密码</param>   
 96         /// <returns>是否压缩成功</returns>   
 97         public  bool ZipDirectory(string folderToZip, string zipedFile, string password)
 98         {
 99             bool result = false;
100             if (!Directory.Exists(folderToZip))
101                 return result;
102 
103             ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
104             zipStream.SetLevel(6);
105             if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
106 
107             result = ZipDirectory(folderToZip, zipStream, "");
108 
109             zipStream.Finish();
110             zipStream.Close();
111 
112             return result;
113         }
114 
115         /// <summary>   
116         /// 压缩文件夹   
117         /// </summary>   
118         /// <param name="folderToZip">要压缩的文件夹路径</param>   
119         /// <param name="zipedFile">压缩文件完整路径</param>   
120         /// <returns>是否压缩成功</returns>   
121         public  bool ZipDirectory(string folderToZip, string zipedFile)
122         {
123             bool result = ZipDirectory(folderToZip, zipedFile, null);
124             return result;
125         }
126 
127         /// <summary>   
128         /// 压缩文件   
129         /// </summary>   
130         /// <param name="fileToZip">要压缩的文件全名</param>   
131         /// <param name="zipedFile">压缩后的文件名</param>   
132         /// <param name="password">密码</param>   
133         /// <returns>压缩结果</returns>   
134         public  bool ZipFile(string fileToZip, string zipedFile, string password)
135         {
136             bool result = true;
137             ZipOutputStream zipStream = null;
138             FileStream fs = null;
139             ZipEntry ent = null;
140 
141             if (!File.Exists(fileToZip))
142                 return false;
143 
144             try
145             {
146                 fs = File.OpenRead(fileToZip);
147                 byte[] buffer = new byte[fs.Length];
148                 fs.Read(buffer, 0, buffer.Length);
149                 fs.Close();
150 
151                 fs = File.Create(zipedFile);
152                 zipStream = new ZipOutputStream(fs);
153                 if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
154                 ent = new ZipEntry(Path.GetFileName(fileToZip));
155                 zipStream.PutNextEntry(ent);
156                 zipStream.SetLevel(6);
157 
158                 zipStream.Write(buffer, 0, buffer.Length);
159 
160             }
161             catch
162             {
163                 result = false;
164             }
165             finally
166             {
167                 if (zipStream != null)
168                 {
169                     zipStream.Finish();
170                     zipStream.Close();
171                 }
172                 if (ent != null)
173                 {
174                     ent = null;
175                 }
176                 if (fs != null)
177                 {
178                     fs.Close();
179                     fs.Dispose();
180                 }
181             }
182             GC.Collect();
183             GC.Collect(1);
184 
185             return result;
186         }
187 
188         /// <summary>   
189         /// 压缩文件   
190         /// </summary>   
191         /// <param name="fileToZip">要压缩的文件全名</param>   
192         /// <param name="zipedFile">压缩后的文件名</param>   
193         /// <returns>压缩结果</returns>   
194         public  bool ZipFile(string fileToZip, string zipedFile)
195         {
196             bool result = ZipFile(fileToZip, zipedFile, null);
197             return result;
198         }
199 
200         /// <summary>   
201         /// 压缩文件或文件夹   
202         /// </summary>   
203         /// <param name="fileToZip">要压缩的路径</param>   
204         /// <param name="zipedFile">压缩后的文件名</param>   
205         /// <param name="password">密码</param>   
206         /// <returns>压缩结果</returns>   
207         public  bool Zip(string fileToZip, string zipedFile, string password)
208         {
209             bool result = false;
210             if (Directory.Exists(fileToZip))
211             {
212                 this.rootPath = Path.GetDirectoryName(fileToZip);
213                 result = ZipDirectory(fileToZip, zipedFile, password);
214             }
215             else if (File.Exists(fileToZip))
216             {
217                 this.rootPath = Path.GetDirectoryName(fileToZip);
218                 result = ZipFile(fileToZip, zipedFile, password);
219             }
220             return result;
221         }
222 
223         /// <summary>   
224         /// 压缩文件或文件夹   
225         /// </summary>   
226         /// <param name="fileToZip">要压缩的路径</param>   
227         /// <param name="zipedFile">压缩后的文件名</param>   
228         /// <returns>压缩结果</returns>   
229         public  bool Zip(string fileToZip, string zipedFile)
230         {
231             bool result = Zip(fileToZip, zipedFile, null);
232             return result;
233 
234         }
235 
236         #endregion
237 
238         #region 解压  
239 
240         /// <summary>   
241         /// 解压功能(解压压缩文件到指定目录)   
242         /// </summary>   
243         /// <param name="fileToUnZip">待解压的文件</param>   
244         /// <param name="zipedFolder">指定解压目标目录</param>   
245         /// <param name="password">密码</param>   
246         /// <returns>解压结果</returns>   
247         public bool UnZip(string fileToUnZip, string zipedFolder, string password)
248         {
249             bool result = true;
250             FileStream fs = null;
251             ZipInputStream zipStream = null;
252             ZipEntry ent = null;
253             string fileName;
254 
255             if (!File.Exists(fileToUnZip))
256                 return false;
257 
258             if (!Directory.Exists(zipedFolder))
259                 Directory.CreateDirectory(zipedFolder);
260 
261             try
262             {
263                 zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
264                 if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
265                 while ((ent = zipStream.GetNextEntry()) != null)
266                 {
267                     if (!string.IsNullOrEmpty(ent.Name))
268                     {
269                         fileName = Path.Combine(zipedFolder, ent.Name);
270                         fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi   
271 
272                         if (fileName.EndsWith("\\"))
273                         {
274                             Directory.CreateDirectory(fileName);
275                             continue;
276                         }
277 
278                         fs = File.Create(fileName);
279                         int size = 2048;
280                         byte[] data = new byte[size];
281                         while (true)
282                         {
283                             size = zipStream.Read(data, 0, data.Length);
284                             if (size > 0)
285                                 fs.Write(data, 0, data.Length);
286                             else
287                                 break;
288                         }
289                     }
290                 }
291             }
292             catch
293             {
294                 result = false;
295             }
296             finally
297             {
298                 if (fs != null)
299                 {
300                     fs.Close();
301                     fs.Dispose();
302                 }
303                 if (zipStream != null)
304                 {
305                     zipStream.Close();
306                     zipStream.Dispose();
307                 }
308                 if (ent != null)
309                 {
310                     ent = null;
311                 }
312                 GC.Collect();
313                 GC.Collect(1);
314             }
315             return result;
316         }
317 
318         /// <summary>   
319         /// 解压功能(解压压缩文件到指定目录)   
320         /// </summary>   
321         /// <param name="fileToUnZip">待解压的文件</param>   
322         /// <param name="zipedFolder">指定解压目标目录</param>   
323         /// <returns>解压结果</returns>   
324         public bool UnZip(string fileToUnZip, string zipedFolder)
325         {
326             bool result = UnZip(fileToUnZip, zipedFolder, null);
327             return result;
328         }
329 
330         #endregion
331     }
332 }
View Code

备注

关于生成压缩的方法还有很多,如通过命令行调用winrar的执行文件,SharpZipLib只是方法之一。

关于SharpZipLib的的API文档,可参看链接

关于源码下载链接

 

出处:https://www.cnblogs.com/hsiang/p/9721423.html

posted on 2014-09-08 16:52  jack_Meng  阅读(2718)  评论(0编辑  收藏  举报

导航