日期:2011-06-22  浏览次数:20387 次

(一). 实现功能
    对文件及目录的压缩及解压功能
(二). 运行图片示例

  (三).代码

   1. 压缩类

 

  1/**//// <summary>
  2/// 压缩类
  3/// </summary>
  4public class ZipClass
  5{  
  6    public static void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
  7    {
  8        //如果文件没有找到,则报错
  9        if (!System.IO.File.Exists(FileToZip))
 10        {
 11            throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
 12        }
 13
 14        System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
 15        System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
 16        ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
 17        ZipEntry ZipEntry = new ZipEntry("ZippedFile");
 18        ZipStream.PutNextEntry(ZipEntry);
 19        ZipStream.SetLevel(CompressionLevel);
 20        byte[] buffer = new byte[BlockSize];
 21        System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
 22        ZipStream.Write(buffer, 0, size);
 23        try
 24        {
 25            while (size < StreamToZip.Length)
 26            {
 27                int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
 28                ZipStream.Write(buffer, 0, sizeRead);
 29                size += sizeRead;
 30            }
 31        }
 32        catch (System.Exception ex)
 33        {
 34            throw ex;
 35        }
 36        ZipStream.Finish();
 37        ZipStream.Close();
 38        StreamToZip.Close();
 39    }
 40
 41    /**//// <summary>
 42    /// 压缩目录
 43    /// </summary>
 44    /// <param name="args">数组(数组[0]: 要压缩的目录; 数组[1]: 压缩的文件名)</param>
 45    public static void ZipFileDictory(string[] args)
 46    {
 47