.Net 下利用ICSharpCode.SharpZipLib.dll实现文件压缩、解压缩

添加引用ICSharpCode.SharpZipLib.dll

 

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.IO;   
  4. using System.Threading;   
  5. using ICSharpCode.SharpZipLib.Zip;   
  6.   
  7. namespace Lib   
  8. {   
  9.     /// <summary>   
  10.     /// 文件压缩、解压缩   
  11.     /// </summary>   
  12.     public class FileCompression   
  13.     {   
  14.         /// <summary>   
  15.         /// 构造函数   
  16.         /// </summary>   
  17.         public FileCompression()   
  18.         {   
  19.         }  
  20.         #region 加密、压缩文件   
  21.         /// <summary>   
  22.         /// 压缩文件   
  23.         /// </summary>   
  24.         /// <param name="fileNames">要打包的文件列表</param>   
  25.         /// <param name="GzipFileName">目标文件名</param>   
  26.         /// <param name="CompressionLevel">压缩品质级别(0~9)</param>   
  27.         /// <param name="SleepTimer">休眠时间(单位毫秒)</param>        
  28.         public static void Compress(List<FileInfo> fileNames, string GzipFileName, int CompressionLevel, int SleepTimer)   
  29.         {   
  30.             ZipOutputStream s = new ZipOutputStream(File.Create(GzipFileName));   
  31.             try  
  32.             {   
  33.                 s.SetLevel(CompressionLevel);   //0 - store only to 9 - means best compression   
  34.                 foreach (FileInfo file in fileNames)   
  35.                 {   
  36.                     FileStream fs = null;   
  37.                     try  
  38.                     {   
  39.                         fs = file.Open(FileMode.Open, FileAccess.ReadWrite);   
  40.                     }   
  41.                     catch  
  42.                     { continue; }                      
  43.                     //  方法二,将文件分批读入缓冲区   
  44.                     byte[] data = new byte[2048];   
  45.                     int size = 2048;   
  46.                     ZipEntry entry = new ZipEntry(Path.GetFileName(file.Name));   
  47.                     entry.DateTime = (file.CreationTime > file.LastWriteTime ? file.LastWriteTime : file.CreationTime);   
  48.                     s.PutNextEntry(entry);   
  49.                     while (true)   
  50.                     {   
  51.                         size = fs.Read(data, 0, size);   
  52.                         if (size <= 0) break;                          
  53.                         s.Write(data, 0, size);   
  54.                     }   
  55.                     fs.Close();   
  56.                     file.Delete();   
  57.                     Thread.Sleep(SleepTimer);   
  58.                 }   
  59.             }   
  60.             finally  
  61.             {   
  62.                 s.Finish();   
  63.                 s.Close();   
  64.             }   
  65.         }  
  66.         #endregion  
  67.         #region 解密、解压缩文件   
  68.         /// <summary>   
  69.         /// 解压缩文件   
  70.         /// </summary>   
  71.         /// <param name="GzipFile">压缩包文件名</param>   
  72.         /// <param name="targetPath">解压缩目标路径</param>          
  73.         public static void Decompress(string GzipFile, string targetPath)   
  74.         {    
  75.             //string directoryName = Path.GetDirectoryName(targetPath + "\\") + "\\";   
  76.             string directoryName = targetPath;   
  77.             if (!Directory.Exists(directoryName)) Directory.CreateDirectory(directoryName);//生成解压目录   
  78.             string CurrentDirectory = directoryName;   
  79.             byte[] data = new byte[2048];   
  80.             int size = 2048;   
  81.             ZipEntry theEntry = null;              
  82.             using (ZipInputStream s = new ZipInputStream(File.OpenRead(GzipFile)))   
  83.             {   
  84.                 while ((theEntry = s.GetNextEntry()) != null)   
  85.                 {   
  86.                     if (theEntry.IsDirectory)   
  87.                     {// 该结点是目录   
  88.                         if (!Directory.Exists(CurrentDirectory + theEntry.Name)) Directory.CreateDirectory(CurrentDirectory + theEntry.Name);   
  89.                     }   
  90.                     else  
  91.                     {   
  92.                         if (theEntry.Name != String.Empty)   
  93.                         {   
  94.                             //解压文件到指定的目录   
  95.                             using (FileStream streamWriter = File.Create(CurrentDirectory + theEntry.Name))   
  96.                             {   
  97.                                 while (true)   
  98.                                 {   
  99.                                     size = s.Read(data, 0, data.Length);   
  100.                                     if (size <= 0) break;   
  101.                                       
  102.                                     streamWriter.Write(data, 0, size);   
  103.                                 }   
  104.                                 streamWriter.Close();   
  105.                             }   
  106.                         }   
  107.                     }   
  108.                 }   
  109.                 s.Close();   
  110.             }              
  111.         }  
  112.         #endregion   
  113.     }   
  114. }  

前台调用:

/// <summary>
    /// 压缩
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnCompress_Click(object sender, EventArgs e)
    {
        String path = Server.MapPath("~/Files/");
        // 检查文件是否存在
        if (File.Exists(path + "第2章 使用数据库.pdf"))
        {
            FileInfo fi1 = new FileInfo(path + "第2章 使用数据库.pdf");
            FileInfo fi2 = new FileInfo(path + "第3章 使用数据绑定和DataSet.pdf");
            FileInfo fi3 = new FileInfo(path + "第4章 SQL Server XML的功能.pdf");
            FileInfo fi4 = new FileInfo(path + "第5章 XML编程.pdf");
            List<FileInfo> fileList = new List<FileInfo>();
            fileList.Add(fi1);
            fileList.Add(fi2);
            fileList.Add(fi3);
            fileList.Add(fi4);
            //  调用方法
            string targetZipFilePath = Server.MapPath("~/ZipFile/") + "Book.zip";// 扩展名可随意
            Lib.FileCompression.Compress(fileList, targetZipFilePath, 5, 5);
            Response.Write("文件压缩成功,请在ZipFile文件夹查看。");
        }
        else
        {
            Response.Write("被压缩文件不存在,请先解压文件。");
        }     

    }

    /// <summary>
    /// 解压缩
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnDecompress_Click(object sender, EventArgs e)
    {
        string zipFilePath = Server.MapPath("~/ZipFile/") + "Book.zip";//
        if (File.Exists(zipFilePath))
        {
            string targetPath = Server.MapPath("~/Files/");
            Lib.FileCompression.Decompress(zipFilePath, targetPath);
            ////  解压后要删除zip文件
            //File.Delete(zipFilePath);
            Response.Write("文件解压成功,请在Files文件夹查看。");
        }
        else
        {
            Response.Write("压缩文件不存在,请先压缩文件。");
        }
    }
}

 

 

 

 

posted @ 2011-06-01 14:00  dodo-yufan  阅读(8906)  评论(0编辑  收藏  举报