压缩、解压缩

http://blog.csdn.net/fhzh520/article/details/1491900

 

最近在网上查了一下在.net中进行压缩和解压缩的方法,方法有很多,我找到了以下几种:

1.利用.net自带的压缩和解压缩方法GZip

参考代码如下:

  1. //========================================================================  
  2.     //  类名: CommonCompress  
  3.     /// <summary>  
  4.     /// 用于对文件和字符串进行压缩  
  5.     /// </summary>  
  6.     /// <remarks>  
  7.     /// 用于对文件和字符串进行压缩  
  8.     /// </remarks>  
  9.     /*=======================================================================  
  10.     变更记录  
  11.     序号   更新日期  开发者   变更内容  
  12.     0001   2008/07/22  张          新建  
  13.     =======================================================================*/  
  14.     public class CommonCompress  
  15.     {  
  16.         /// <summary>  
  17.         /// 压缩字符串  
  18.         /// </summary>  
  19.         /// <param name="strUncompressed">未压缩的字符串</param>  
  20.         /// <returns>压缩的字符串</returns>  
  21.         public static string StringCompress(string strUncompressed)  
  22.         {  
  23.             byte[] bytData = System.Text.Encoding.Unicode.GetBytes(strUncompressed);  
  24.             MemoryStream ms = new MemoryStream();  
  25.             Stream s = new GZipStream(ms, CompressionMode.Compress);  
  26.             s.Write(bytData, 0, bytData.Length);  
  27.             s.Close();  
  28.             byte[] dataCompressed = (byte[])ms.ToArray();  
  29.             return System.Convert.ToBase64String(dataCompressed, 0, dataCompressed.Length);  
  30.         }  
  31.   
  32.         /// <summary>  
  33.         /// 解压缩字符串  
  34.         /// </summary>  
  35.         /// <param name="strCompressed">压缩的字符串</param>  
  36.         /// <returns>未压缩的字符串</returns>  
  37.         public static string StringDeCompress(string strCompressed)  
  38.         {  
  39.             System.Text.StringBuilder strUncompressed = new System.Text.StringBuilder();  
  40.             int totalLength = 0;  
  41.             byte[] bInput = System.Convert.FromBase64String(strCompressed); ;  
  42.             byte[] dataWrite = new byte[4096];  
  43.             Stream s = new GZipStream(new MemoryStream(bInput), CompressionMode.Decompress);  
  44.             while (true)  
  45.             {  
  46.                 int size = s.Read(dataWrite, 0, dataWrite.Length);  
  47.                 if (size > 0)  
  48.                 {  
  49.                     totalLength += size;  
  50.                     strUncompressed.Append(System.Text.Encoding.Unicode.GetString(dataWrite, 0, size));  
  51.                 }  
  52.                 else  
  53.                 {  
  54.                     break;  
  55.                 }  
  56.             }  
  57.             s.Close();  
  58.             return strUncompressed.ToString();  
  59.         }  
  60.   
  61.         /// <summary>  
  62.         /// 压缩文件  
  63.         /// </summary>  
  64.         /// <param name="iFile">压缩前文件路径</param>  
  65.         /// <param name="oFile">压缩后文件路径</param>  
  66.         public static void CompressFile(string iFile, string oFile)  
  67.         {  
  68.             //判断文件是否存在  
  69.             if (File.Exists(iFile) == false)  
  70.             {  
  71.                 throw new FileNotFoundException("文件未找到!");  
  72.             }  
  73.             //创建文件流  
  74.             byte[] buffer = null;  
  75.             FileStream iStream = null;  
  76.             FileStream oStream = null;  
  77.             GZipStream cStream = null;  
  78.             try  
  79.             {  
  80.                 //把文件写进数组  
  81.                 iStream = new FileStream(iFile, FileMode.Open, FileAccess.Read, FileShare.Read);  
  82.                 buffer = new byte[iStream.Length];  
  83.                 int num = iStream.Read(buffer, 0, buffer.Length);  
  84.                 if (num != buffer.Length)  
  85.                 {  
  86.                     throw new ApplicationException("压缩文件异常!");  
  87.                 }  
  88.                 //创建文件输出流并输出  
  89.                 oStream = new FileStream(oFile, FileMode.OpenOrCreate, FileAccess.Write);  
  90.                 cStream = new GZipStream(oStream, CompressionMode.Compress, true);  
  91.                 cStream.Write(buffer, 0, buffer.Length);  
  92.             }  
  93.             finally  
  94.             {  
  95.                 //关闭流对象  
  96.                 if (iStream != null) iStream.Close();  
  97.                 if (cStream != null) cStream.Close();  
  98.                 if (oStream != null) oStream.Close();  
  99.             }  
  100.         }  
  101.   
  102.         /// <summary>  
  103.         /// 解压缩文件  
  104.         /// </summary>  
  105.         /// <param name="iFile">压缩前文件路径</param>  
  106.         /// <param name="oFile">压缩后文件路径</param>  
  107.         public static void DecompressFile(string iFile, string oFile)  
  108.         {  
  109.             //判断文件是否存在  
  110.             if (File.Exists(iFile) == false)  
  111.             {  
  112.                 throw new FileNotFoundException("文件未找到!");  
  113.             }  
  114.             //创建文件流  
  115.             FileStream iStream = null;  
  116.             FileStream oStream = null;  
  117.             GZipStream dStream = null;  
  118.             byte[] qBuffer = new byte[4];  
  119.             try  
  120.             {  
  121.                 //把压缩文件写入数组  
  122.                 iStream = new FileStream(iFile, FileMode.Open);  
  123.                 dStream = new GZipStream(iStream, CompressionMode.Decompress, true);  
  124.                 int position = (int)iStream.Length - 4;  
  125.                 iStream.Position = position;  
  126.                 iStream.Read(qBuffer, 0, 4);  
  127.                 iStream.Position = 0;  
  128.                 int num = BitConverter.ToInt32(qBuffer, 0);  
  129.                 byte[] buffer = new byte[num + 100];  
  130.                 int offset = 0total = 0;  
  131.                 while (true)  
  132.                 {  
  133.                     int bytesRead = dStream.Read(buffer, offset, 100);  
  134.                     if (bytesRead == 0) break;  
  135.                     offset += bytesRead;  
  136.                     total += bytesRead;  
  137.                 }  
  138.                 //创建输出流并输出  
  139.                 oStream = new FileStream(oFile, FileMode.Create);  
  140.                 oStream.Write(buffer, 0, total);  
  141.                 oStream.Flush();  
  142.             }  
  143.             finally  
  144.             {  
  145.                 //关闭流对象  
  146.                 if (iStream != null) iStream.Close();  
  147.                 if (dStream != null) dStream.Close();  
  148.                 if (oStream != null) oStream.Close();  
  149.             }  
  150.         }  
  151.     }  
//========================================================================
    //  类名: CommonCompress
    /// <summary>
    /// 用于对文件和字符串进行压缩
    /// </summary>
    /// <remarks>
    /// 用于对文件和字符串进行压缩
    /// </remarks>
    /*=======================================================================
    变更记录
    序号   更新日期  开发者   变更内容
    0001   2008/07/22  张          新建
    =======================================================================*/
    public class CommonCompress
    {
        /// <summary>
        /// 压缩字符串
        /// </summary>
        /// <param name="strUncompressed">未压缩的字符串</param>
        /// <returns>压缩的字符串</returns>
        public static string StringCompress(string strUncompressed)
        {
            byte[] bytData = System.Text.Encoding.Unicode.GetBytes(strUncompressed);
            MemoryStream ms = new MemoryStream();
            Stream s = new GZipStream(ms, CompressionMode.Compress);
            s.Write(bytData, 0, bytData.Length);
            s.Close();
            byte[] dataCompressed = (byte[])ms.ToArray();
            return System.Convert.ToBase64String(dataCompressed, 0, dataCompressed.Length);
        }

        /// <summary>
        /// 解压缩字符串
        /// </summary>
        /// <param name="strCompressed">压缩的字符串</param>
        /// <returns>未压缩的字符串</returns>
        public static string StringDeCompress(string strCompressed)
        {
            System.Text.StringBuilder strUncompressed = new System.Text.StringBuilder();
            int totalLength = 0;
            byte[] bInput = System.Convert.FromBase64String(strCompressed); ;
            byte[] dataWrite = new byte[4096];
            Stream s = new GZipStream(new MemoryStream(bInput), CompressionMode.Decompress);
            while (true)
            {
                int size = s.Read(dataWrite, 0, dataWrite.Length);
                if (size > 0)
                {
                    totalLength += size;
                    strUncompressed.Append(System.Text.Encoding.Unicode.GetString(dataWrite, 0, size));
                }
                else
                {
                    break;
                }
            }
            s.Close();
            return strUncompressed.ToString();
        }

        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="iFile">压缩前文件路径</param>
        /// <param name="oFile">压缩后文件路径</param>
        public static void CompressFile(string iFile, string oFile)
        {
            //判断文件是否存在
            if (File.Exists(iFile) == false)
            {
                throw new FileNotFoundException("文件未找到!");
            }
            //创建文件流
            byte[] buffer = null;
            FileStream iStream = null;
            FileStream oStream = null;
            GZipStream cStream = null;
            try
            {
                //把文件写进数组
                iStream = new FileStream(iFile, FileMode.Open, FileAccess.Read, FileShare.Read);
                buffer = new byte[iStream.Length];
                int num = iStream.Read(buffer, 0, buffer.Length);
                if (num != buffer.Length)
                {
                    throw new ApplicationException("压缩文件异常!");
                }
                //创建文件输出流并输出
                oStream = new FileStream(oFile, FileMode.OpenOrCreate, FileAccess.Write);
                cStream = new GZipStream(oStream, CompressionMode.Compress, true);
                cStream.Write(buffer, 0, buffer.Length);
            }
            finally
            {
                //关闭流对象
                if (iStream != null) iStream.Close();
                if (cStream != null) cStream.Close();
                if (oStream != null) oStream.Close();
            }
        }

        /// <summary>
        /// 解压缩文件
        /// </summary>
        /// <param name="iFile">压缩前文件路径</param>
        /// <param name="oFile">压缩后文件路径</param>
        public static void DecompressFile(string iFile, string oFile)
        {
            //判断文件是否存在
            if (File.Exists(iFile) == false)
            {
                throw new FileNotFoundException("文件未找到!");
            }
            //创建文件流
            FileStream iStream = null;
            FileStream oStream = null;
            GZipStream dStream = null;
            byte[] qBuffer = new byte[4];
            try
            {
                //把压缩文件写入数组
                iStream = new FileStream(iFile, FileMode.Open);
                dStream = new GZipStream(iStream, CompressionMode.Decompress, true);
                int position = (int)iStream.Length - 4;
                iStream.Position = position;
                iStream.Read(qBuffer, 0, 4);
                iStream.Position = 0;
                int num = BitConverter.ToInt32(qBuffer, 0);
                byte[] buffer = new byte[num + 100];
                int offset = 0, total = 0;
                while (true)
                {
                    int bytesRead = dStream.Read(buffer, offset, 100);
                    if (bytesRead == 0) break;
                    offset += bytesRead;
                    total += bytesRead;
                }
                //创建输出流并输出
                oStream = new FileStream(oFile, FileMode.Create);
                oStream.Write(buffer, 0, total);
                oStream.Flush();
            }
            finally
            {
                //关闭流对象
                if (iStream != null) iStream.Close();
                if (dStream != null) dStream.Close();
                if (oStream != null) oStream.Close();
            }
        }
    }


 

2.利用ICSharpCode的压缩和解压缩方法,需引用ICSharpCode.SharpZipLib.dll,这个类库是开源的,源码地址http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx
参考代码如下:
  1. using System;  
  2. using System.Collections.Generic;   
  3. using System.IO;  
  4.   
  5. using ICSharpCode.SharpZipLib.Zip;  
  6. using ICSharpCode.SharpZipLib.Checksums;  
  7.   
  8. namespace ZYBNET.FW.Utility.CommonMethod  
  9. {  
  10.     //========================================================================   
  11.     //  类名: ZipHelper   
  12.     /// <summary>   
  13.     /// 用于对文件和字符串进行压缩   
  14.     /// </summary>   
  15.     /// <remarks>   
  16.     /// 用于对文件和字符串进行压缩   
  17.     /// </remarks>   
  18.     /*======================================================================= 
  19.     变更记录 
  20.     序号   更新日期  开发者   变更内容 
  21.     0001   2008/07/22  张          新建 
  22.     =======================================================================*/  
  23.     public class ZipHelper  
  24.     {  
  25.         #region 压缩文件夹,支持递归   
  26.         /// <summary>   
  27.         /// 压缩文件夹   
  28.         /// </summary>   
  29.         /// <param name="dir">待压缩的文件夹</param>   
  30.         /// <param name="targetFileName">压缩后文件路径(包括文件名)</param>   
  31.         /// <param name="recursive">是否递归压缩</param>   
  32.         /// <returns></returns>   
  33.         public static bool Compress(string dir, string targetFileName, bool recursive)  
  34.         {  
  35.             //如果已经存在目标文件,询问用户是否覆盖   
  36.             if (File.Exists(targetFileName))  
  37.             {  
  38.                 throw new Exception("同名文件已经存在!");  
  39.             }  
  40.             string[] ars = new string[2];  
  41.             if (recursive == false)  
  42.             {  
  43.                 ars[0] = dir;  
  44.                 ars[1] = targetFileName;  
  45.                 return ZipFileDictory(ars);  
  46.             }  
  47.   
  48.             FileStream zipFile;  
  49.             ZipOutputStream zipStream;  
  50.   
  51.             //打开压缩文件流   
  52.             zipFile = File.Create(targetFileName);  
  53.             zipStream = new ZipOutputStream(zipFile);  
  54.   
  55.             if (dir != String.Empty)  
  56.             {  
  57.                 CompressFolder(dir, zipStream, dir);  
  58.             }  
  59.   
  60.             //关闭压缩文件流   
  61.             zipStream.Finish();  
  62.             zipStream.Close();  
  63.   
  64.             if (File.Exists(targetFileName))  
  65.                 return true;  
  66.             else  
  67.                 return false;  
  68.         }  
  69.   
  70.         /// <summary>   
  71.         /// 压缩目录   
  72.         /// </summary>   
  73.         /// <param name="args">数组(数组[0]: 要压缩的目录; 数组[1]: 压缩的文件名)</param>   
  74.         public static bool ZipFileDictory(string[] args)  
  75.         {  
  76.             ZipOutputStream zStream = null;  
  77.             try  
  78.             {  
  79.                 string[] filenames = Directory.GetFiles(args[0]);  
  80.                 Crc32 crc = new Crc32();  
  81.                 zStream = new ZipOutputStream(File.Create(args[1]));  
  82.                 zStream.SetLevel(6);  
  83.                 //循环压缩文件夹中的文件   
  84.                 foreach (string file in filenames)  
  85.                 {  
  86.                     //打开压缩文件   
  87.                     FileStream fs = File.OpenRead(file);  
  88.                     byte[] buffer = new byte[fs.Length];  
  89.                     fs.Read(buffer, 0, buffer.Length);  
  90.                     ZipEntry entry = new ZipEntry(file);  
  91.                     entry.DateTime = DateTime.Now;  
  92.                     entry.Size = fs.Length;  
  93.                     fs.Close();  
  94.                     crc.Reset();  
  95.                     crc.Update(buffer);  
  96.                     entry.Crc = crc.Value;  
  97.                     zStream.PutNextEntry(entry);  
  98.                     zStream.Write(buffer, 0, buffer.Length);  
  99.                 }  
  100.             }  
  101.             catch  
  102.             {  
  103.                 throw;  
  104.             }  
  105.             finally  
  106.             {  
  107.                 zStream.Finish();  
  108.                 zStream.Close();  
  109.             }  
  110.             return true;  
  111.         }  
  112.   
  113.         /// <summary>   
  114.         /// 压缩某个子文件夹   
  115.         /// </summary>   
  116.         /// <param name="basePath">待压缩路径</param>   
  117.         /// <param name="zips">压缩文件流</param>   
  118.         /// <param name="zipfolername">待压缩根路径</param>        
  119.         private static void CompressFolder(string basePath, ZipOutputStream zips, string zipfolername)  
  120.         {  
  121.             if (File.Exists(basePath))  
  122.             {  
  123.                 AddFile(basePath, zips, zipfolername);  
  124.                 return;  
  125.             }  
  126.             string[] names = Directory.GetFiles(basePath);  
  127.             foreach (string fileName in names)  
  128.             {  
  129.                 AddFile(fileName, zips, zipfolername);  
  130.             }  
  131.   
  132.             names = Directory.GetDirectories(basePath);  
  133.             foreach (string folderName in names)  
  134.             {  
  135.                 CompressFolder(folderName, zips, zipfolername);  
  136.             }  
  137.   
  138.         }  
  139.   
  140.         /// <summary>   
  141.         /// 压缩某个子文件   
  142.         /// </summary>   
  143.         /// <param name="fileName">待压缩文件</param>   
  144.         /// <param name="zips">压缩流</param>   
  145.         /// <param name="zipfolername">待压缩根路径</param>   
  146.         private static void AddFile(string fileName, ZipOutputStream zips, string zipfolername)  
  147.         {  
  148.             if (File.Exists(fileName))  
  149.             {  
  150.                 CreateZipFile(fileName, zips, zipfolername);  
  151.             }  
  152.         }  
  153.   
  154.         /// <summary>   
  155.         /// 压缩单独文件   
  156.         /// </summary>   
  157.         /// <param name="FileToZip">待压缩文件</param>   
  158.         /// <param name="zips">压缩流</param>   
  159.         /// <param name="zipfolername">待压缩根路径</param>   
  160.         private static void CreateZipFile(string FileToZip, ZipOutputStream zips, string zipfolername)  
  161.         {  
  162.             try  
  163.             {  
  164.                 FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read);  
  165.                 string temp = FileToZip;  
  166.                 string temp1 = zipfolername;  
  167.                 if (temp1.Length > 0)  
  168.                 {  
  169.                     temp = temp.Replace(zipfolername + "\\", "");  
  170.                 }  
  171.                 ZipEntry ZipEn = new ZipEntry(temp);  
  172.   
  173.                 zips.PutNextEntry(ZipEn);  
  174.                 byte[] buffer = new byte[16384];  
  175.                 System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);  
  176.                 zips.Write(buffer, 0, size);  
  177.                 try  
  178.                 {  
  179.                     while (size < StreamToZip.Length)  
  180.                     {  
  181.                         int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);  
  182.                         zips.Write(buffer, 0, sizeRead);  
  183.                         size += sizeRead;  
  184.                     }  
  185.                 }  
  186.                 catch (System.Exception ex)  
  187.                 {  
  188.                     throw ex;  
  189.                 }  
  190.   
  191.                 StreamToZip.Close();  
  192.             }  
  193.             catch  
  194.             {  
  195.                 throw;  
  196.             }  
  197.         }  
  198.         #endregion  
  199.  
  200.         #region 解压缩   
  201.         /// <summary>      
  202.         /// 功能:解压zip格式的文件。      
  203.         /// </summary>      
  204.         /// <param name="zipFilePath">压缩文件路径</param>      
  205.         /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>      
  206.         /// <returns>解压是否成功</returns>      
  207.         public static void UnZipFile(string zipFilePath, string unZipDir)  
  208.         {  
  209.    
  210.             if (zipFilePath == string.Empty)  
  211.             {  
  212.                 throw new Exception("压缩文件不能为空!");  
  213.             }  
  214.             if (!File.Exists(zipFilePath))  
  215.             {  
  216.                 throw new Exception("压缩文件不存在!");  
  217.             }  
  218.             //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹      
  219.             if (unZipDir == string.Empty)  
  220.                 unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));  
  221.             if (!unZipDir.EndsWith("//"))  
  222.                 unZipDir += "//";  
  223.             if (!Directory.Exists(unZipDir))  
  224.                 Directory.CreateDirectory(unZipDir);  
  225.   
  226.             try  
  227.             {  
  228.                 using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))  
  229.                 {  
  230.                     ZipEntry theEntry;  
  231.                     while ((theEntry = s.GetNextEntry()) != null)  
  232.                     {  
  233.                         string directoryName = Path.GetDirectoryName(theEntry.Name);  
  234.                         string fileName = Path.GetFileName(theEntry.Name);  
  235.                         if (directoryName.Length > 0)  
  236.                         {  
  237.                             Directory.CreateDirectory(unZipDir + directoryName);  
  238.                         }  
  239.                         if (!directoryName.EndsWith("//"))  
  240.                             directoryName += "//";  
  241.                         if (fileName != String.Empty)  
  242.                         {  
  243.                             using (FileStream streamWriter = File.Create(unZipDir + theEntry.Name))  
  244.                             {  
  245.                                 int size = 2048;  
  246.                                 byte[] data = new byte[2048];  
  247.                                 while (true)  
  248.                                 {  
  249.                                     size = s.Read(data, 0, data.Length);  
  250.                                     if (size > 0)  
  251.                                     {  
  252.                                         streamWriter.Write(data, 0, size);  
  253.                                     }  
  254.                                     else  
  255.                                     {  
  256.                                         break;  
  257.                                     }  
  258.                                 }  
  259.                             }  
  260.                         }  
  261.                     }  
  262.                 }  
  263.             }  
  264.             catch   
  265.             {  
  266.                 throw;  
  267.             }  
  268.         }  
  269.         #endregion   
  270.   
  271.     }  
  272. }  
  273.   
  274.    
using System;
using System.Collections.Generic; 
using System.IO;

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;

namespace ZYBNET.FW.Utility.CommonMethod
{
    //========================================================================
    //  类名: ZipHelper
    /// <summary>
    /// 用于对文件和字符串进行压缩
    /// </summary>
    /// <remarks>
    /// 用于对文件和字符串进行压缩
    /// </remarks>
    /*=======================================================================
    变更记录
    序号   更新日期  开发者   变更内容
    0001   2008/07/22  张          新建
    =======================================================================*/
    public class ZipHelper
    {
        #region 压缩文件夹,支持递归
        /// <summary>
        /// 压缩文件夹
        /// </summary>
        /// <param name="dir">待压缩的文件夹</param>
        /// <param name="targetFileName">压缩后文件路径(包括文件名)</param>
        /// <param name="recursive">是否递归压缩</param>
        /// <returns></returns>
        public static bool Compress(string dir, string targetFileName, bool recursive)
        {
            //如果已经存在目标文件,询问用户是否覆盖
            if (File.Exists(targetFileName))
            {
                throw new Exception("同名文件已经存在!");
            }
            string[] ars = new string[2];
            if (recursive == false)
            {
                ars[0] = dir;
                ars[1] = targetFileName;
                return ZipFileDictory(ars);
            }

            FileStream zipFile;
            ZipOutputStream zipStream;

            //打开压缩文件流
            zipFile = File.Create(targetFileName);
            zipStream = new ZipOutputStream(zipFile);

            if (dir != String.Empty)
            {
                CompressFolder(dir, zipStream, dir);
            }

            //关闭压缩文件流
            zipStream.Finish();
            zipStream.Close();

            if (File.Exists(targetFileName))
                return true;
            else
                return false;
        }

        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="args">数组(数组[0]: 要压缩的目录; 数组[1]: 压缩的文件名)</param>
        public static bool ZipFileDictory(string[] args)
        {
            ZipOutputStream zStream = null;
            try
            {
                string[] filenames = Directory.GetFiles(args[0]);
                Crc32 crc = new Crc32();
                zStream = new ZipOutputStream(File.Create(args[1]));
                zStream.SetLevel(6);
                //循环压缩文件夹中的文件
                foreach (string file in filenames)
                {
                    //打开压缩文件
                    FileStream fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ZipEntry entry = new ZipEntry(file);
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    zStream.PutNextEntry(entry);
                    zStream.Write(buffer, 0, buffer.Length);
                }
            }
            catch
            {
                throw;
            }
            finally
            {
                zStream.Finish();
                zStream.Close();
            }
            return true;
        }

        /// <summary>
        /// 压缩某个子文件夹
        /// </summary>
        /// <param name="basePath">待压缩路径</param>
        /// <param name="zips">压缩文件流</param>
        /// <param name="zipfolername">待压缩根路径</param>     
        private static void CompressFolder(string basePath, ZipOutputStream zips, string zipfolername)
        {
            if (File.Exists(basePath))
            {
                AddFile(basePath, zips, zipfolername);
                return;
            }
            string[] names = Directory.GetFiles(basePath);
            foreach (string fileName in names)
            {
                AddFile(fileName, zips, zipfolername);
            }

            names = Directory.GetDirectories(basePath);
            foreach (string folderName in names)
            {
                CompressFolder(folderName, zips, zipfolername);
            }

        }

        /// <summary>
        /// 压缩某个子文件
        /// </summary>
        /// <param name="fileName">待压缩文件</param>
        /// <param name="zips">压缩流</param>
        /// <param name="zipfolername">待压缩根路径</param>
        private static void AddFile(string fileName, ZipOutputStream zips, string zipfolername)
        {
            if (File.Exists(fileName))
            {
                CreateZipFile(fileName, zips, zipfolername);
            }
        }

        /// <summary>
        /// 压缩单独文件
        /// </summary>
        /// <param name="FileToZip">待压缩文件</param>
        /// <param name="zips">压缩流</param>
        /// <param name="zipfolername">待压缩根路径</param>
        private static void CreateZipFile(string FileToZip, ZipOutputStream zips, string zipfolername)
        {
            try
            {
                FileStream StreamToZip = new FileStream(FileToZip, FileMode.Open, FileAccess.Read);
                string temp = FileToZip;
                string temp1 = zipfolername;
                if (temp1.Length > 0)
                {
                    temp = temp.Replace(zipfolername + "\\", "");
                }
                ZipEntry ZipEn = new ZipEntry(temp);

                zips.PutNextEntry(ZipEn);
                byte[] buffer = new byte[16384];
                System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
                zips.Write(buffer, 0, size);
                try
                {
                    while (size < StreamToZip.Length)
                    {
                        int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                        zips.Write(buffer, 0, sizeRead);
                        size += sizeRead;
                    }
                }
                catch (System.Exception ex)
                {
                    throw ex;
                }

                StreamToZip.Close();
            }
            catch
            {
                throw;
            }
        }
        #endregion

        #region 解压缩
        /// <summary>   
        /// 功能:解压zip格式的文件。   
        /// </summary>   
        /// <param name="zipFilePath">压缩文件路径</param>   
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>   
        /// <returns>解压是否成功</returns>   
        public static void UnZipFile(string zipFilePath, string unZipDir)
        {
 
            if (zipFilePath == string.Empty)
            {
                throw new Exception("压缩文件不能为空!");
            }
            if (!File.Exists(zipFilePath))
            {
                throw new Exception("压缩文件不存在!");
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹   
            if (unZipDir == string.Empty)
                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 > 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;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch 
            {
                throw;
            }
        }
        #endregion

    }
}

 
3.利用java的压缩和解压缩方法,需引用vjslib.dll

至于这种方法的使用,大家可以去查阅msdn,这里就不写了

4.利用zlibwapi.dll的API进行压缩

据说压缩效率比较好,但是在网上没找到供下载的链接,有兴趣的朋友可以试试

5.使用System.IO.Packaging压缩和解压

System.IO.Packaging在WindowsBase.dll程序集下,使用时需要添加对WindowsBase的引用

  1. /// <summary>   
  2.         /// Add a folder along with its subfolders to a Package   
  3.         /// </summary>   
  4.         /// <param name="folderName">The folder to add</param>   
  5.         /// <param name="compressedFileName">The package to create</param>   
  6.         /// <param name="overrideExisting">Override exsisitng files</param>   
  7.         /// <returns></returns>   
  8.         static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)  
  9.         {  
  10.             if (folderName.EndsWith(@"\"))  
  11.                 folderName = folderName.Remove(folderName.Length - 1);  
  12.             bool result = false;  
  13.             if (!Directory.Exists(folderName))  
  14.             {  
  15.                 return result;  
  16.             }  
  17.   
  18.             if (!overrideExisting && File.Exists(compressedFileName))  
  19.             {  
  20.                 return result;  
  21.             }  
  22.             try  
  23.             {  
  24.                 using (Package package = Package.Open(compressedFileName, FileMode.Create))  
  25.                 {  
  26.                     var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);  
  27.                     foreach (string fileName in fileList)  
  28.                     {  
  29.                          
  30.                         //The path in the package is all of the subfolders after folderName   
  31.                         string pathInPackage;  
  32.                         pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);  
  33.   
  34.                         Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));  
  35.                         PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);  
  36.                         using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))  
  37.                         {  
  38.                             fileStream.CopyTo(packagePartDocument.GetStream());  
  39.                         }  
  40.                     }  
  41.                 }  
  42.                 result = true;  
  43.             }  
  44.             catch (Exception e)  
  45.             {  
  46.                 throw new Exception("Error zipping folder " + folderName, e);  
  47.             }  
  48.              
  49.             return result;  
  50.         }  
  51.   
  52.   
  53.  /// <summary>   
  54.         /// Compress a file into a ZIP archive as the container store   
  55.         /// </summary>   
  56.         /// <param name="fileName">The file to compress</param>   
  57.         /// <param name="compressedFileName">The archive file</param>   
  58.         /// <param name="overrideExisting">override existing file</param>   
  59.         /// <returns></returns>   
  60.         static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting)  
  61.         {  
  62.             bool result = false;  
  63.   
  64.             if (!File.Exists(fileName))  
  65.             {  
  66.                 return result;  
  67.             }  
  68.   
  69.             if (!overrideExisting && File.Exists(compressedFileName))  
  70.             {  
  71.                 return result;  
  72.             }  
  73.   
  74.             try  
  75.             {  
  76.                 Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative));  
  77.                  
  78.                 using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))  
  79.                 {  
  80.                     if (package.PartExists(partUriDocument))  
  81.                     {  
  82.                         package.DeletePart(partUriDocument);  
  83.                     }   
  84.   
  85.                     PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);  
  86.                     using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))  
  87.                     {  
  88.                         fileStream.CopyTo(packagePartDocument.GetStream());  
  89.                     }  
  90.                 }  
  91.                 result = true;  
  92.             }  
  93.             catch (Exception e)  
  94.             {  
  95.                 throw new Exception("Error zipping file " + fileName, e);  
  96.             }  
  97.               
  98.             return result;  
  99.         }  
  100.   
  101.   
  102. }       3、zip文件解压  
  103.   
  104. Code/// <summary>   
  105.         /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification   
  106.         /// </summary>   
  107.         /// <param name="folderName">The folder to extract the package to</param>   
  108.         /// <param name="compressedFileName">The package file</param>   
  109.         /// <param name="overrideExisting">override existing files</param>   
  110.         /// <returns></returns>   
  111.         static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)  
  112.         {  
  113.             bool result = false;  
  114.             try  
  115.             {  
  116.                 if (!File.Exists(compressedFileName))  
  117.                 {  
  118.                     return result;  
  119.                 }  
  120.   
  121.                 DirectoryInfo directoryInfo = new DirectoryInfo(folderName);  
  122.                 if (!directoryInfo.Exists)  
  123.                     directoryInfo.Create();  
  124.   
  125.                 using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))  
  126.                 {  
  127.                     foreach (PackagePart packagePart in package.GetParts())  
  128.                     {  
  129.                         ExtractPart(packagePart, folderName, overrideExisting);  
  130.                     }  
  131.                 }  
  132.   
  133.                 result = true;  
  134.             }  
  135.             catch (Exception e)  
  136.             {  
  137.                 throw new Exception("Error unzipping file " + compressedFileName, e);  
  138.             }  
  139.               
  140.             return result;  
  141.         }  
  142.   
  143.         static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)  
  144.         {  
  145.             string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');  
  146.   
  147.             if (!Directory.Exists(Path.GetDirectoryName(stringPart)))  
  148.                 Directory.CreateDirectory(Path.GetDirectoryName(stringPart));  
  149.   
  150.             if (!overrideExisting && File.Exists(stringPart))  
  151.                 return;  
  152.             using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))  
  153.             {  
  154.                 packagePart.GetStream().CopyTo(fileStream);  
  155.             }  
  156.         }  
/// <summary>
        /// Add a folder along with its subfolders to a Package
        /// </summary>
        /// <param name="folderName">The folder to add</param>
        /// <param name="compressedFileName">The package to create</param>
        /// <param name="overrideExisting">Override exsisitng files</param>
        /// <returns></returns>
        static bool PackageFolder(string folderName, string compressedFileName, bool overrideExisting)
        {
            if (folderName.EndsWith(@"\"))
                folderName = folderName.Remove(folderName.Length - 1);
            bool result = false;
            if (!Directory.Exists(folderName))
            {
                return result;
            }

            if (!overrideExisting && File.Exists(compressedFileName))
            {
                return result;
            }
            try
            {
                using (Package package = Package.Open(compressedFileName, FileMode.Create))
                {
                    var fileList = Directory.EnumerateFiles(folderName, "*", SearchOption.AllDirectories);
                    foreach (string fileName in fileList)
                    {
                       
                        //The path in the package is all of the subfolders after folderName
                        string pathInPackage;
                        pathInPackage = Path.GetDirectoryName(fileName).Replace(folderName, string.Empty) + "/" + Path.GetFileName(fileName);

                        Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(pathInPackage, UriKind.Relative));
                        PackagePart packagePartDocument = package.CreatePart(partUriDocument,"", CompressionOption.Maximum);
                        using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                        {
                            fileStream.CopyTo(packagePartDocument.GetStream());
                        }
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error zipping folder " + folderName, e);
            }
           
            return result;
        }


 /// <summary>
        /// Compress a file into a ZIP archive as the container store
        /// </summary>
        /// <param name="fileName">The file to compress</param>
        /// <param name="compressedFileName">The archive file</param>
        /// <param name="overrideExisting">override existing file</param>
        /// <returns></returns>
        static bool PackageFile(string fileName, string compressedFileName, bool overrideExisting)
        {
            bool result = false;

            if (!File.Exists(fileName))
            {
                return result;
            }

            if (!overrideExisting && File.Exists(compressedFileName))
            {
                return result;
            }

            try
            {
                Uri partUriDocument = PackUriHelper.CreatePartUri(new Uri(Path.GetFileName(fileName), UriKind.Relative));
               
                using (Package package = Package.Open(compressedFileName, FileMode.OpenOrCreate))
                {
                    if (package.PartExists(partUriDocument))
                    {
                        package.DeletePart(partUriDocument);
                    } 

                    PackagePart packagePartDocument = package.CreatePart(partUriDocument, "", CompressionOption.Maximum);
                    using (FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                    {
                        fileStream.CopyTo(packagePartDocument.GetStream());
                    }
                }
                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error zipping file " + fileName, e);
            }
            
            return result;
        }


}       3、zip文件解压

Code/// <summary>
        /// Extract a container Zip. NOTE: container must be created as Open Packaging Conventions (OPC) specification
        /// </summary>
        /// <param name="folderName">The folder to extract the package to</param>
        /// <param name="compressedFileName">The package file</param>
        /// <param name="overrideExisting">override existing files</param>
        /// <returns></returns>
        static bool UncompressFile(string folderName, string compressedFileName, bool overrideExisting)
        {
            bool result = false;
            try
            {
                if (!File.Exists(compressedFileName))
                {
                    return result;
                }

                DirectoryInfo directoryInfo = new DirectoryInfo(folderName);
                if (!directoryInfo.Exists)
                    directoryInfo.Create();

                using (Package package = Package.Open(compressedFileName, FileMode.Open, FileAccess.Read))
                {
                    foreach (PackagePart packagePart in package.GetParts())
                    {
                        ExtractPart(packagePart, folderName, overrideExisting);
                    }
                }

                result = true;
            }
            catch (Exception e)
            {
                throw new Exception("Error unzipping file " + compressedFileName, e);
            }
            
            return result;
        }

        static void ExtractPart(PackagePart packagePart, string targetDirectory, bool overrideExisting)
        {
            string stringPart = targetDirectory + HttpUtility.UrlDecode(packagePart.Uri.ToString()).Replace('\\', '/');

            if (!Directory.Exists(Path.GetDirectoryName(stringPart)))
                Directory.CreateDirectory(Path.GetDirectoryName(stringPart));

            if (!overrideExisting && File.Exists(stringPart))
                return;
            using (FileStream fileStream = new FileStream(stringPart, FileMode.Create))
            {
                packagePart.GetStream().CopyTo(fileStream);
            }
        }


6.在.NET 4.5使用ZipArchive、ZipFile等类压缩和解压

  1. static void Main(string[] args)  
  2.        {  
  3.            string ZipPath = @"c:\users\exampleuser\start.zip";  
  4.            string ExtractPath = @"c:\users\exampleuser\extract";  
  5.            string NewFile = @"c:\users\exampleuser\NewFile.txt";  
  6.   
  7.            using (ZipArchive Archive = ZipFile.Open(ZipPath, ZipArchiveMode.Update))  
  8.            {  
  9.                Archive.CreateEntryFromFile(NewFile, "NewEntry.txt");  
  10.                Archive.ExtractToDirectory(ExtractPath);  
  11.            }   
  12.        }  

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值