SharpZip压缩解压

  组件下载地址:

http://sourceforge.net/projects/sharpdevelop/files/SharpZipLib/

 

 

  
  
  
  
  1. using System;                                        
  2. using System.Collections.Generic;                                        
  3. using System.IO;                                     
  4. using ICSharpCode.SharpZipLib.Checksums;                                     
  5. using ICSharpCode.SharpZipLib.Zip;                                       
  6.                                      
  7. namespace SharpZipLib压缩                                      
  8. {                                        
  9.     /// <summary>                                        
  10.     /// 压缩和解压文件                                      
  11.     /// </summary>                                       
  12.     public class ZipClass                                        
  13.     {                                        
  14.         /// <summary>                                        
  15.         /// 所有文件缓存                                       
  16.         /// </summary>                                       
  17.         List<string> files = new List<string>();    
  18.    
  19.         /// <summary>    
  20.         /// 所有空目录缓存    
  21.         /// </summary>    
  22.         List<string> paths = new List<string>();    
  23.    
  24.         /// <summary>    
  25.         /// 压缩单个文件    
  26.         /// </summary>    
  27.         /// <param name="fileToZip">要压缩的文件</param>    
  28.         /// <param name="zipedFile">压缩后的文件全名</param>    
  29.         /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>    
  30.         /// <param name="blockSize">分块大小</param>    
  31.         public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize)    
  32.         {    
  33.             if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错    
  34.             {    
  35.                 throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");    
  36.             }    
  37.    
  38.             FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);    
  39.             FileStream zipFile = File.Create(zipedFile);    
  40.             ZipOutputStream zipStream = new ZipOutputStream(zipFile);    
  41.             ZipEntry zipEntry = new ZipEntry(fileToZip);    
  42.             zipStream.PutNextEntry(zipEntry);    
  43.             zipStream.SetLevel(compressionLevel);    
  44.             byte[] buffer = new byte[blockSize];    
  45.             int size = streamToZip.Read(buffer, 0, buffer.Length);    
  46.             zipStream.Write(buffer, 0, size);    
  47.    
  48.             try   
  49.             {    
  50.                 while (size < streamToZip.Length)    
  51.                 {    
  52.                     int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);    
  53.                     zipStream.Write(buffer, 0, sizeRead);    
  54.                     size += sizeRead;    
  55.                 }    
  56.             }    
  57.             catch (Exception ex)    
  58.             {    
  59.                 throw ex;    
  60.             }    
  61.    
  62.             zipStream.Finish();    
  63.             zipStream.Close();    
  64.             streamToZip.Close();    
  65.         }    
  66.    
  67.         /// <summary>    
  68.         /// 压缩目录(包括子目录及所有文件)    
  69.         /// </summary>    
  70.         /// <param name="rootPath">要压缩的根目录</param>    
  71.         /// <param name="destinationPath">保存路径</param>    
  72.         /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>    
  73.         public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel)    
  74.         {    
  75.             GetAllDirectories(rootPath);    
  76.    
  77.             /*            while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾   
  78.                         {   
  79.   
  80.                             rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\"   
  81.   
  82.                         }   
  83.             */   
  84.             //string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。    
  85.             string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。    
  86.             Crc32 crc = new Crc32();    
  87.             ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));    
  88.             outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression    
  89.             foreach (string file in files)    
  90.             {    
  91.                 FileStream fileStream = File.OpenRead(file);//打开压缩文件    
  92.                 byte[] buffer = new byte[fileStream.Length];    
  93.                 fileStream.Read(buffer, 0, buffer.Length);    
  94.                 ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));    
  95.                 entry.DateTime = DateTime.Now;    
  96.                 // set Size and the crc, because the information    
  97.                 // about the size and crc should be stored in the header    
  98.                 // if it is not set it is automatically written in the footer.    
  99.                 // (in this case size == crc == -1 in the header)    
  100.                 // Some ZIP programs have problems with zip files that don't store    
  101.                 // the size and crc in the header.    
  102.                 entry.Size = fileStream.Length;    
  103.                 fileStream.Close();    
  104.                 crc.Reset();    
  105.                 crc.Update(buffer);    
  106.                 entry.Crc = crc.Value;    
  107.                 outPutStream.PutNextEntry(entry);    
  108.                 outPutStream.Write(buffer, 0, buffer.Length);    
  109.             }    
  110.    
  111.             this.files.Clear();    
  112.    
  113.             foreach (string emptyPath in paths)    
  114.             {    
  115.                 ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");    
  116.                 outPutStream.PutNextEntry(entry);    
  117.             }    
  118.    
  119.             this.paths.Clear();    
  120.             outPutStream.Finish();    
  121.             outPutStream.Close();    
  122.         }    
  123.    
  124.         /// <summary>    
  125.         /// 取得目录下所有文件及文件夹,分别存入files及paths    
  126.         /// </summary>    
  127.         /// <param name="rootPath">根目录</param>    
  128.         private void GetAllDirectories(string rootPath)    
  129.         {    
  130.             string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录    
  131.             foreach (string path in subPaths)    
  132.             {    
  133.                 GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List    
  134.             }    
  135.             string[] files = Directory.GetFiles(rootPath);    
  136.             foreach (string file in files)    
  137.             {    
  138.                 this.files.Add(file);//将当前目录中的所有文件全名存入文件List    
  139.             }    
  140.             if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录    
  141.             {    
  142.                 this.paths.Add(rootPath);//记录空目录    
  143.             }    
  144.         }    
  145.    
  146.         /// <summary>    
  147.         /// 解压缩文件(压缩文件中含有子目录)    
  148.         /// </summary>    
  149.         /// <param name="zipfilepath">待解压缩的文件路径</param>    
  150.         /// <param name="unzippath">解压缩到指定目录</param>    
  151.         /// <returns>解压后的文件列表</returns>    
  152.         public List<string> UnZip(string zipfilepath, string unzippath)    
  153.         {    
  154.             //解压出来的文件列表    
  155.             List<string> unzipFiles = new List<string>();    
  156.    
  157.             //检查输出目录是否以“\\”结尾    
  158.             if (unzippath.EndsWith("\\")==false||unzippath.EndsWith(":\\")==false)    
  159.             {    
  160.                 unzippath += "\\";    
  161.             }    
  162.    
  163.             ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));    
  164.             ZipEntry theEntry;    
  165.             while ((theEntry = s.GetNextEntry()) != null)    
  166.             {    
  167.                 string directoryName = Path.GetDirectoryName(unzippath);    
  168.                 string fileName = Path.GetFileName(theEntry.Name);    
  169.    
  170.                 //生成解压目录【用户解压到硬盘根目录时,不需要创建】    
  171.                 if (!string.IsNullOrEmpty(directoryName))    
  172.                 {    
  173.                     Directory.CreateDirectory(directoryName);    
  174.                 }    
  175.    
  176.                 if (fileName != String.Empty)    
  177.                 {    
  178.                     //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入    
  179.                     if (theEntry.CompressedSize == 0)    
  180.                         break;    
  181.                     //解压文件到指定的目录    
  182.                     directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);    
  183.                     //建立下面的目录和子目录    
  184.                     Directory.CreateDirectory(directoryName);    
  185.                         
  186.                     //记录导出的文件    
  187.                     unzipFiles.Add(unzippath + theEntry.Name);    
  188.    
  189.                     FileStream streamWriter = File.Create(unzippath + theEntry.Name);    
  190.    
  191.                     int size = 2048;    
  192.                     byte[] data = new byte[2048];    
  193.                     while (true)    
  194.                     {    
  195.                         size = s.Read(data, 0, data.Length);    
  196.                         if (size > 0)    
  197.                         {    
  198.                             streamWriter.Write(data, 0, size);    
  199.                         }    
  200.                         else   
  201.                         {    
  202.                             break;    
  203.                         }    
  204.                     }    
  205.                     streamWriter.Close();    
  206.                 }    
  207.             }    
  208.             s.Close();    
  209.    
  210.             return unzipFiles;    
  211.         }    
  212.     }    
  213. }   

你可能感兴趣的:(职场,休闲,压缩解压,SharpZip)