使用SharpZipLib实现zip压缩

使用国外开源加压解压库ICSharpCode.SharpZipLib实现加压,该库的官方网站为
http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx

使用体验:可以照着例子实现简单的加压解压,可以加压一个文件夹中的所有文件,但没有提供加压子文件夹的说明。
目前网上的一些代码有的无法加压空文件夹,有的加压了用rar解不开,这是一点需要改进的。
但如果只需要加压文件夹第一级子目录中的“文件”(不包括文件夹和子目录)的情况,使用这个库是很方便的。而且是正常zip格式。
比.Net提供的GZipStream类强在它可以按照标准zip格式加压多个文件,而GZipStream没有提供加压多个文件的方法,需要自己定义,
这样解压也只有使用自己的程序才可以,通用性方面不如SharpZipLib。

#region 加压解压方法
        /// <summary>
        /// 功能:压缩文件(暂时只压缩文件夹下一级目录中的文件,文件夹及其子级被忽略)
        /// </summary>
        /// <param name="dirPath">被压缩的文件夹夹路径</param>
        /// <param name="zipFilePath">生成压缩文件的路径,为空则默认与被压缩文件夹同一级目录,名称为:文件夹名+.zip</param>
        /// <param name="err">出错信息</param>
        /// <returns>是否压缩成功</returns>
        public bool ZipFile(string dirPath, string zipFilePath, out string err)
        {
            err = "";
            if (dirPath == string.Empty)
            {
                err = "要压缩的文件夹不能为空!";
                return false;
            }
            if (!Directory.Exists(dirPath))
            {
                err = "要压缩的文件夹不存在!";
                return false;
            }
            //压缩文件名为空时使用文件夹名+.zip
            if (zipFilePath == string.Empty)
            {
                if (dirPath.EndsWith("\\"))
                {
                    dirPath = dirPath.Substring(0, dirPath.Length - 1);
                }
                zipFilePath = dirPath + ".zip";
            }

try
            {
                string[] filenames = Directory.GetFiles(dirPath);
                using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))
                {
                    s.SetLevel(9);
                    byte[] buffer = new byte[4096];
                    foreach (string file in filenames)
                    {
                        ZipEntry entry = new ZipEntry(Path.GetFileName(file));
                        entry.DateTime = DateTime.Now;
                        s.PutNextEntry(entry);
                        using (FileStream fs = File.OpenRead(file))
                        {
                            int sourceBytes;
                            do
                            {
                                sourceBytes = fs.Read(buffer, 0, buffer.Length);
                                s.Write(buffer, 0, sourceBytes);
                            } while (sourceBytes > 0);
                        }
                    }
                    s.Finish();
                    s.Close();
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }

/// <summary>
        /// 功能:解压zip格式的文件。
        /// </summary>
        /// <param name="zipFilePath">压缩文件路径</param>
        /// <param name="unZipDir">解压文件存放路径,为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹</param>
        /// <param name="err">出错信息</param>
        /// <returns>解压是否成功</returns>
        public bool UnZipFile(string zipFilePath, string unZipDir, out string err)
        {
            err = "";
            if (zipFilePath == string.Empty)
            {
                err = "压缩文件不能为空!";
                return false;
            }
            if (!File.Exists(zipFilePath))
            {
                err = "压缩文件不存在!";
                return false;
            }
            //解压文件夹为空时默认与压缩文件同一级目录下,跟压缩文件同名的文件夹
            if (unZipDir == string.Empty)
                unZipDir = zipFilePath.Replace(Path.GetFileName(zipFilePath), Path.GetFileNameWithoutExtension(zipFilePath));
            if (!unZipDir.EndsWith("\\"))
                unZipDir += "\\";
            if (!Directory.Exists(unZipDir))
                Directory.CreateDirectory(unZipDir);

try
            {
                using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))
                {

ZipEntry theEntry;
                    while ((theEntry = s.GetNextEntry()) != null)
                    {
                        string directoryName = Path.GetDirectoryName(theEntry.Name);
                        string fileName = Path.GetFileName(theEntry.Name);
                        if (directoryName.Length > 0)
                        {
                            Directory.CreateDirectory(unZipDir + directoryName);
                        }
                        if (!directoryName.EndsWith("\\"))
                            directoryName += "\\";
                        if (fileName != String.Empty)
                        {
                            using (FileStream streamWriter = File.Create(unZipDir + 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;
                                    }
                                }
                            }
                        }
                    }//while
                }
            }
            catch (Exception ex)
            {
                err = ex.Message;
                return false;
            }
            return true;
        }//解压结束
        #endregion

需要添加对SharpZipLib的引用:

using ICSharpCode.SharpZipLib.Zip;

时间: 2024-08-26 19:52:31

使用SharpZipLib实现zip压缩的相关文章

C#实现Zip压缩解压实例【转】

本文只列举一个压缩帮助类,使用的是有要添加一个dll引用ICSharpCode.SharpZipLib.dll[下载地址]. 另外说明一下的是,这个类压缩格式是ZIP的,所以文件的后缀写成 .zip. 还有,如果用这个类来解压rar格式的压缩文件时会报错,就网上说的那个"Wrong Local header signature: 0x21726152"异常.只要解压ZIP压缩格式的压缩文件就不会报错了. 下面就是Helper类的代码: using System; using Syste

ASP.NET打包生成zip压缩文件

using System; using System.Collections.Generic; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.IO; using System.Drawing; using System.Drawing.Imaging; using System.Drawing.Drawing2D; using Microsoft.Win32; using

C#实现多级子目录Zip压缩解压实例

? ? 参考 https://blog.csdn.net/lki_suidongdong/article/details/20942977 重点: 实现多级子目录的压缩,类似winrar,可以选择是否排除基准目录 ? ? ? ? ? ? ? ? ? ? 测试代码 ? ? public?void?ZipDirectoryTest()??? {??? string?path?=?System.IO.Path.Combine(System.IO.Path.GetTempPath(),?DateTime

使用SharpZIpLib写的压缩解压操作类

使用SharpZIpLib写的压缩解压操作类,已测试. public class ZipHelper { /// <summary> /// 压缩文件 /// </summary> /// <param name="directory"></param> /// <param name="targetPath"></param> public static void Zip(string dir

java基础----&gt;Zip压缩的使用(转)

java中提供了对压缩格式的数据流的读写.它们封装到现成的IO 类中,以提供压缩功能.下面我们开始java中压缩文件的使用. 目录导航: 关于压缩的简要说明 GZIP压缩文件的使用 ZIP压缩文件的使用 GZIP与ZIP压缩的比较 友情链接 关于压缩的简要说明 一. Java中有着压缩的类: CheckedInputStream GetCheckSum()为任何InputStream 产生校验和(不仅是解压) CheckedOutputStream GetCheckSum()为任何OutputS

Java使用Zip压缩文件或整个目录

1.压缩文件或整个目录 import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.zip.ZipEntry

ZIP压缩格式与RAR压缩格式

早已习惯了安装系统之后必须安装winrar,压缩文件也已经习惯了rar格式,这种习惯的力量真的挺可怕的.在工作中你的同事可能没有安装winrar,或者他们不喜欢安装盗版软件,这时候你给他们发送过去的是rar文件就会给他们造成麻烦.然而新安装的系统不管是XP还是win7都是原生支持ZIP的,所以为了不给他人造成困扰我决定以后一律用ZIP压缩文件. 其实在公司的一些规范里面也应该推广ZIP格式以便大家能更方便的工作.

java基础之zip(压缩、解压)

本程序依赖第三方包Ant.jar.因为java自带的java.utils.zip.ZipOutputStream对一些敏感中文路径会抛出异常. package javax.zip; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.Ou

正确的 zip 压缩与解压代码

网上流传的zip压缩与解压 的代码有很大的问题 虽然使用了ant进行压缩与解压,但是任务的流程还是用的java.util.zip 的方式写的,我在使用的过程中遇到了压缩的目录结构有误,甚至出现不同解压软件显示的目录结构不同的窘境. 下面给出使用org.apache.tools.ant.taskdefs.Zip;和org.apache.tools.ant.taskdefs.Expand 的压缩和解压过程. import java.io.File; import org.apache.tools.a