/// <summary>
 /// 压缩文件
 /// </summary>

using System;
using System.IO;

using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.GZip;

namespace FtpResume.Utility
{
    public class ZipClass
    {
        public string cutStr = "";

public void ZipFile(string FileToZip, string ZipedFile, int CompressionLevel, int BlockSize)
        {
            //如果文件没有找到则报错。
            if (!System.IO.File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("The specified file " + FileToZip + " could not be found. Zipping aborderd");
            }

System.IO.FileStream StreamToZip = new System.IO.FileStream(FileToZip, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            System.IO.FileStream ZipFile = System.IO.File.Create(ZipedFile);
            ZipOutputStream ZipStream = new ZipOutputStream(ZipFile);
            ZipEntry ZipEntry = new ZipEntry("ZippedFile");
            ZipStream.PutNextEntry(ZipEntry);
            ZipStream.SetLevel(CompressionLevel);
            byte[] buffer = new byte[BlockSize];
            System.Int32 size = StreamToZip.Read(buffer, 0, buffer.Length);
            ZipStream.Write(buffer, 0, size);
            try
            {
                while (size < StreamToZip.Length)
                {
                    int sizeRead = StreamToZip.Read(buffer, 0, buffer.Length);
                    ZipStream.Write(buffer, 0, sizeRead);
                    size += sizeRead;
                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            ZipStream.Finish();
            ZipStream.Close();
            StreamToZip.Close();
        }

//Get all DirectoryInfo
        private void direct(DirectoryInfo di, ref ZipOutputStream s, Crc32 crc)
        {
            //DirectoryInfo di = new DirectoryInfo(filenames);
            DirectoryInfo[] dirs = di.GetDirectories("*");

//遍历目录下面的所有的子目录
            foreach (DirectoryInfo dirNext in dirs)
            {
                //将该目录下的所有文件添加到 ZipOutputStream s 压缩流里面
                FileInfo[] a = dirNext.GetFiles();
                this.writeStream(ref s, a, crc);

//递归调用直到把所有的目录遍历完成
                direct(dirNext, ref s, crc);
            }
        }

private void writeStream(ref ZipOutputStream s, FileInfo[] a, Crc32 crc)
        {
            foreach (FileInfo fi in a)
            {
                //string fifn = fi.FullName;
                FileStream fs = fi.OpenRead();

byte[] buffer = new byte[fs.Length];
                fs.Read(buffer, 0, buffer.Length);

//ZipEntry entry = new ZipEntry(file);    Path.GetFileName(file)
                string file = fi.FullName;
                file = file.Replace(cutStr, "");

ZipEntry entry = new ZipEntry(file);

entry.DateTime = DateTime.Now;

// set Size and the crc, because the information
                // about the size and crc should be stored in the header
                // if it is not set it is automatically written in the footer.
                // (in this case size == crc == -1 in the header)
                // Some ZIP programs have problems with zip files that don't store
                // the size and crc in the header.
                entry.Size = fs.Length;
                fs.Close();

crc.Reset();
                crc.Update(buffer);

entry.Crc = crc.Value;

s.PutNextEntry(entry);

s.Write(buffer, 0, buffer.Length);
            }
        }

/// <summary>
        /// 压缩指定目录下指定文件(包括子目录下的文件)
        /// </summary>
        /// <param name="zippath">args[0]为你要压缩的目录所在的路径
        /// 例如:D:\\temp\\   (注意temp 后面加 \\ 但是你写程序的时候怎么修改都可以)</param>
        /// <param name="zipfilename">args[1]为压缩后的文件名及其路径
        /// 例如:D:\\temp.zip</param>
        /// <param name="fileFilter">文件过滤, 例如*.xml,这样只压缩.xml文件.</param>
        ///
        public bool ZipFileMain(string zippath, string zipfilename, string fileFilter)
        {
            try
            {
                //string filenames = Directory.GetFiles(args[0]);

Crc32 crc = new Crc32();
                ZipOutputStream s = new ZipOutputStream(File.Create(zipfilename));

s.SetLevel(6); // 0 - store only to 9 - means best compression

DirectoryInfo di = new DirectoryInfo(zippath);

FileInfo[] a = di.GetFiles(fileFilter);

cutStr = zippath.Trim();
                //压缩这个目录下的所有文件
                writeStream(ref s, a, crc);
                //压缩这个目录下子目录及其文件
                direct(di, ref s, crc);

s.Finish();
                s.Close();
            }
            catch
            {
                return false;
            }
            return true;
        }
    }
}

///<summary>
///解压缩文件
///</summary>
using System;
using System.Text;
using System.Collections;
using System.IO;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters.Binary;
using System.Data;

using ICSharpCode.SharpZipLib.BZip2;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;
using ICSharpCode.SharpZipLib.GZip;

namespace FtpResume.Utility
{
    public class UnZipClass
    {
        /// <summary>
        /// 解压缩文件(压缩文件中含有子目录)
        /// </summary>
        /// <param name="zipfilepath">待解压缩的文件路径</param>
        /// <param name="unzippath">解压缩到指定目录</param>
        public void UnZip(string zipfilepath, string unzippath)
        {
            ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));

ZipEntry theEntry;
            while ((theEntry = s.GetNextEntry()) != null)
            {
                string directoryName = Path.GetDirectoryName(unzippath);
                string fileName = Path.GetFileName(theEntry.Name);

//生成解压目录
                Directory.CreateDirectory(directoryName);

if (fileName != String.Empty)
                {
                    //如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入
                    if (theEntry.CompressedSize == 0)
                        break;
                    //解压文件到指定的目录
                    directoryName = Path.GetDirectoryName(unzippath + theEntry.Name);
                    //建立下面的目录和子目录
                    Directory.CreateDirectory(directoryName);

FileStream streamWriter = File.Create(unzippath + 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();
        }
    }
}

转载于:https://www.cnblogs.com/amylis_chen/archive/2011/08/19/2145402.html

C#利用ICSharpCode.SharpZipLib.dll压缩文件和解压文件相关推荐

  1. python zipfile压缩的文件用shell命令解压_Python学习第177课——bzip2、zip方式压缩文件和解压文件...

    之前我们学习了tar打包.解包.gzip压缩,现在我们学习gzip解压. ●gzip解压 现在我们把上节生成的压缩文件linux_compressed.gz进行解压,使用命令: tar -xzf li ...

  2. C# 利用ICSharpCode.SharpZipLib.dll 实现压缩和解压缩文件

    我们 开发时经常会遇到需要压缩文件的需求,利用C#的开源组件ICSharpCode.SharpZipLib, 就可以很容易的实现压缩和解压缩功能. 压缩文件: /// <summary> ...

  3. asp.net利用winrar 压缩文件 和解压文件

    注意: 在服务器端必须安装 winrar 源码: string filepath = Server.MapPath("freezip"); string strtxtPath = ...

  4. mac 上传文件和解压文件

    打开终端 上传文件选择 "安全文件传输(sftp)" 填写用户名:第二行填写 sftp 用户名@服务器IP地址 连接linux远程服务器上传下载文件选择sftp是最方便的,点击如图 ...

  5. C#使用ICSharpCode.SharpZipLib.dll压缩文件夹和文件

    大家可以到http://www.icsharpcode.net/opensource/sharpziplib/ 下载SharpZiplib的最新版本,本文使用的版本为0.86.0.518,支持Zip, ...

  6. html解压zip文件怎么打开方式,使用zip.js压缩文件和解压文件

    官方例子支持在线演示效果. 研究的目的是:如何获取zip包中的信息并读取传输(其实使用JAVA或者node.js更容易实现,之所以使用js也是因为业务的特殊性). 准备库: 下载成功解压是这样的,如图 ...

  7. 数据结构实训之——哈夫曼树压缩文件和解压文件(C语言)

    文章目录 实训目的 代码 实验部分截图 心里话♥ 源码+实验报告

  8. C# ZipHelper C#公共类 -- ICSharpCode.SharpZipLib.dll实现压缩和解压

    关于本文档的说明 本文档基于ICSharpCode.SharpZipLib.dll的封装,常用的解压和压缩方法都已经涵盖在内,都是经过项目实战积累下来的 1.基本介绍 由于项目中需要用到各种压缩将文件 ...

  9. zip (ICSharpCode.SharpZipLib.dll文件需要下载)

    ZipClass zc=new ZipClass (); zc.ZipDir(@"E:\1\新建文件夹", @"E:\1\新建文件夹.zip", 1);//压缩 ...

最新文章

  1. easyui的datagrid
  2. Python字符串居然可以这样玩 到底怎么做到的 年薪50w程序员揭晓
  3. 后端程序员必备的Linux基础知识
  4. XCode: 兼容ARC和non-ARC
  5. java隐藏密钥_java – 在Android中隐藏密钥库密码的最佳方法是什么?
  6. Linux下访问光盘数据
  7. 编译原理 —— 1.2 编译系统的结构(终于弄懂语法和语义的区别了!)
  8. 使用 ConnectionStringBuilder 对象创建精确连接字符串
  9. 计算机世界:免费的代价
  10. PS 前端技能一 白色背景图片变为透明的图片
  11. creat是什么意思中文翻译_CREAT是什么意思中文翻译
  12. SVLsimulator与apollo6.0联合仿真
  13. RSF 分布式服务框架设计
  14. linux中搜索文件内容关键字
  15. CSDN Blogger小工具
  16. 前端HTML5面试题
  17. 原腾讯副总裁,Google资深研究员吴军:ChatGPT不算新技术革命,带不来什么新机会...
  18. 如何创建 CAB 文件和如何从文件、内存和资源中解压缩 CAB 文件
  19. MarkDown-符号大全
  20. Sentinel demo

热门文章

  1. react antD moment
  2. 如何表示int的最大值
  3. windows平台搭建Mongo数据库复制集(类似集群)(三)
  4. token,session,cookie
  5. js的apply()与call()的区别
  6. edx错误的地方开始安装
  7. 职业-把工作当作职业 or 事业?
  8. 利用Oracle分析函数实现多行数据合并为一行
  9. 【转】Silverlight 3 Beta 新特性解析(7)- Child Window和Shader Effect篇
  10. Android开发之自定义TabHost文字及背景(源代码分享)