用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

原文地址:https://www.cnblogs.com/mq0036/p/3961514.html