简单SharpZipLib使用方法

SharpZipLib提供了多种压缩算法的支持,纯csharp代码,参见
http://www.icsharpcode.net/OpenSource/SharpZipLib/default.asp,你可以到其官方网站下载最新版本的SharpZipLib:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.asp

该控件是使用csharp写的,因此可以直接在dotnet环境中引用,不需要注册。

利用 SharpZipLib方便地压缩和解压缩文件
最新版本的SharpZipLib(0.84)增加了很多新的功能,其中包括增加了FastZip类,这让我们可以非常方便地把一个目录压缩成一个压缩包,经测试可以很好地支持文件中包含中文以及空格的情况。

将下面的两个方法添加到类中,然后直接调用:

压缩:

 

/// <summary>
  
/// Create a Zip archive.
  
/// </summary>
  
/// <param name="filename">The filename.</param>
  
/// <param name="directory">The directory to Zip.</param> 

   public   static   void  PackFiles( string  filename,  string  directory)
  
{
   
try
   
{
    FastZip fz 
= new FastZip();
    fz.CreateEmptyDirectories 
= true;
    fz.CreateZip(filename, directory, 
true"");
    fz 
= null;
   }

   
catch (Exception)
   
{
    
throw;
   }

  }

解压缩:

  /// <summary>
  /// Unpacks the files.
  /// </summary>
  /// <param name="file">The file.</param>
  /// <returns>if succeed return true,otherwise false.</returns>
  public static bool UnpackFiles(string file, string dir)
  {
   try
   {
    if (!Directory.Exists(dir))
     Directory.CreateDirectory(dir);

    ZipInputStream s = new ZipInputStream(File.OpenRead(file));

    ZipEntry theEntry;
    while ((theEntry = s.GetNextEntry()) != null)
    {

     string directoryName = Path.GetDirectoryName(theEntry.Name);
     string fileName = Path.GetFileName(theEntry.Name);

     if (directoryName != String.Empty)
      Directory.CreateDirectory(dir + directoryName);

     if (fileName != String.Empty)
     {
      FileStream streamWriter = File.Create(dir + 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;
       }
      }

      streamWriter.Close();
     }
    }
    s.Close();
    return true;
   }
   catch (Exception)
   {
    throw;
   }
  }

添加引用:
using ICSharpCode.SharpZipLib.Zip;
using System.IO;
调用方式如下:

假如建立了一个Pack类,在你的代码中添加:

Pack.PackFiles(file,directory);         //Zip  file是你要生成的压缩文件,directory是要压缩的目录,支持子目录。

Pack.UnpackFiles(file,dir);              //UnZip  file是要解压缩的文件,dir是解压路径

SharpZipLib的功能很强大,上面只是实现了简单的压缩、解压,具体的方法还是自己研究。

 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值