如何使用C#压缩文件及注意的问题!

首选,先要找一个开源的C#压缩组件。
如:ICSharpCode.SharpZipLib 下载地址: http://www.icsharpcode.net/OpenSource/SharpZipLib/Default.aspx
根据它的帮助你就可以做自己需要的东东了。
我在使用这个组件行,遇到了一个问题。
当压缩小文件时没有什么错误,一旦源文件达到150M时,它会让你的机器垮掉。(至少是我的机器)
为什么会这样,因为如果源文件是150M时,你就需要在内存申请一个150M大小的字节数组。好点的机器还没问题,一般的机器可就惨了。如果文件在大的话,好机器也受不了的。
为了解决大文件压缩的问题,可以使用分段压缩的方法。

private string CreateZIPFile(string path,int  M)
  {
   try
   {
    Crc32 crc = new Crc32();
    ICSharpCode.SharpZipLib.Zip.ZipOutputStream zipout=new ICSharpCode.SharpZipLib.Zip.ZipOutputStream(System.IO.File.Create(path+".zip"));
    System.IO.FileStream fs=System.IO.File.OpenRead(path);
    long pai=1024*1024*M;//每M兆写一次
    long forint=fs.Length/pai+1;
    byte[] buffer=null;
    ZipEntry entry = new ZipEntry(System.IO.Path.GetFileName(path));
    entry.Size = fs.Length;
    entry.DateTime = DateTime.Now;
    zipout.PutNextEntry(entry);
    for(long i=1;i<=forint;i++)
    {
     if(pai*i<fs.Length)
     {
      buffer = new byte[pai];
      fs.Seek(pai*(i-1),System.IO.SeekOrigin.Begin);
     }
     else
     {
      if(fs.Length<pai)
      {
       buffer = new byte[fs.Length];
      }
      else
      {
       buffer = new byte[fs.Length-pai*(i-1)];
       fs.Seek(pai*(i-1),System.IO.SeekOrigin.Begin);
      }
     }
     fs.Read(buffer,0,buffer.Length);
     crc.Reset();
     crc.Update(buffer);
     zipout.Write(buffer,0, buffer.Length);
     zipout.Flush();
    }
    fs.Close();
    zipout.Finish();
    zipout.Close();
    System.IO.File.Delete(path);
    return path+".zip";
   }
   catch(Exception ex)
   {
    string str=ex.Message;
    return path;
   }   
  }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值