LOGO OA教程 ERP教程 模切知识交流 PMS教程 CRM教程 开发文档 其他文档  
 
网站管理员

C#文件或文件夹压缩和解压方法(通过ICSharpCode.SharpZipLib.dll)

admin
2021年3月8日 10:35 本文热度 3247

我在网上收集一下文件的压缩和解压的方法,是通过ICSharpCode.SharpZipLib.dll 来实现的

一、介绍的目录

第一步:下载压缩和解压的 ICSharpCode.SharpZipLib.dll 支持库

第二步:创建一个压缩和解压的demo项目

第三步:查看压缩和解压的文件的结果


二、demo演示(包括源码和界面)

1、下载文件压缩和解压的支持库dll ,下载地址:附件:文件压缩和解压(SharpZipLib).zip

2、创建window创建项目



1) 添加引用(文件压缩和解压的dll)

 


2) 编写文件压缩和解压方法

选中项目,创建Model文件夹,添加连个类名,压缩类(ZipFloClass)和解压类(UnZipFloClass)

2.1)压缩类(ZipFloClass)

using ICSharpCode.SharpZipLib.Checksums;

using ICSharpCode.SharpZipLib.Zip;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ZipCompressTest.Model

{

    ///

    /// 压缩的方法

    ///

    public  class ZipFloClass

    {

        public void ZipFile(string strFile, string strZip)

        {

            var len = strFile.Length;

            var strlen = strFile[len - 1];

            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)

            {

                strFile += Path.DirectorySeparatorChar;

            }

            ZipOutputStream outstream = new ZipOutputStream(File.Create(strZip));

            outstream.SetLevel(6);

            zip(strFile, outstream, strFile);

            outstream.Finish();

            outstream.Close();

        }

 

        public void zip(string strFile, ZipOutputStream outstream, string staticFile)

        {

            if (strFile[strFile.Length - 1] != Path.DirectorySeparatorChar)

            {

                strFile += Path.DirectorySeparatorChar;

            }

            Crc32 crc = new Crc32();

            //获取指定目录下所有文件和子目录文件名称

            string[] filenames = Directory.GetFileSystemEntries(strFile);

            //遍历文件

            foreach (string file in filenames)

            {

                if (Directory.Exists(file))

                {

                    zip(file, outstream, staticFile);

                }

                //否则,直接压缩文件

                else

                {

                    //打开文件

                    FileStream fs = File.OpenRead(file);

                    //定义缓存区对象

                    byte[] buffer = new byte[fs.Length];

                    //通过字符流,读取文件

                    fs.Read(buffer, 0, buffer.Length);

                    //得到目录下的文件(比如:D:\Debug1\test,test

                    string tempfile = file.Substring(staticFile.LastIndexOf("\\") + 1);

                    ZipEntry entry = new ZipEntry(tempfile);

                    entry.DateTime = DateTime.Now;

                    entry.Size = fs.Length;

                    fs.Close();

                    crc.Reset();

                    crc.Update(buffer);

                    entry.Crc = crc.Value;

                    outstream.PutNextEntry(entry);

                    //写文件

                    outstream.Write(buffer, 0, buffer.Length);

                }

            }

        }

    }

}


2.2)解压类(UnZipFloClass)

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ZipCompressTest.Model
{
    ///
    /// 解压方法
    ///
    public class UnZipFloClass
    {
        public string unZipFile(string TargetFile, string fileDir, ref string msg)
        {
            string rootFile = "";
            msg = "";
            try
            {
                //读取压缩文件(zip文件),准备解压缩
                ZipInputStream inputstream = new ZipInputStream(File.OpenRead(TargetFile.Trim()));
                ZipEntry entry;
                string path = fileDir;
                //解压出来的文件保存路径
                string rootDir = "";
                //根目录下的第一个子文件夹的名称
                while ((entry = inputstream.GetNextEntry()) != null)
                {
                    rootDir = Path.GetDirectoryName(entry.Name);
                    //得到根目录下的第一级子文件夹的名称
                    if (rootDir.IndexOf("\\") >= 0)
                    {
                        rootDir = rootDir.Substring(0, rootDir.IndexOf("\\") + 1);
                    }
                    string dir = Path.GetDirectoryName(entry.Name);
                    //得到根目录下的第一级子文件夹下的子文件夹名称
                    string fileName = Path.GetFileName(entry.Name);
                    //根目录下的文件名称
                    if (dir != "")
                    {
                        //创建根目录下的子文件夹,不限制级别
                        if (!Directory.Exists(fileDir + "\\" + dir))
                        {
                            path = fileDir + "\\" + dir;
                            //在指定的路径创建文件夹
                            Directory.CreateDirectory(path);
                        }
                    }
                    else if (dir == "" && fileName != "")
                    {
                        //根目录下的文件
                        path = fileDir;
                        rootFile = fileName;
                    }
                    else if (dir != "" && fileName != "")
                    {
                        //根目录下的第一级子文件夹下的文件
                        if (dir.IndexOf("\\") > 0)
                        {
                            //指定文件保存路径
                            path = fileDir + "\\" + dir;
                        }
                    }
                    if (dir == rootDir)
                    {
                        //判断是不是需要保存在根目录下的文件
                        path = fileDir + "\\" + rootDir;
                    }
 
                    //以下为解压zip文件的基本步骤
                    //基本思路:遍历压缩文件里的所有文件,创建一个相同的文件
                    if (fileName != String.Empty)
                    {
                        FileStream fs = File.Create(path + "\\" + fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = inputstream.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                fs.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                        fs.Close();
                    }
                }
                inputstream.Close();
                msg = "解压成功!";
                return rootFile;
            }
            catch (Exception ex)
            {
                msg = "解压失败,原因:" + ex.Message;
                return "1;" + ex.Message;
            }
        }
    }
}


3)窗体页面的调用

3.1)窗体布局



3.2)对应的调用方法

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using ZipCompressTest.Model;
 
namespace ZipCompressTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
 
        ///
        /// 压缩事件
        ///
        ///
        ///
        private void btnZipFlo_Click(object sender, EventArgs e)
        {
            string[] strs = new string[2];
            //待压缩文件目录
            strs[0] = "D:\\DeBug1\\";
            //压缩后的目标文件
            strs[1] = "D:\\Debug2\\FrpTest.zip";
            ZipFloClass zc = new ZipFloClass();
            zc.ZipFile(strs[0], strs[1]);
        }
 
        ///
        /// 解压事件
        ///
        ///
        ///
        private void btnUnZipFlo_Click(object sender, EventArgs e)
        {
            string[] strs = new string[2];
            string msg = "";
            //待解压的文件
            strs[0] = "D:\\Debug2\\FrpTest.zip";
            //解压后放置的目标文件
            strs[1] = "D:\\Debug3\\";
            UnZipFloClass uzc = new UnZipFloClass();
            uzc.unZipFile(strs[0], strs[1], ref msg);
            MessageBox.Show("信息:" + msg);
        }
 
        ///
        /// 批量压缩事件
        ///
        ///
        ///
        private void btnBatchZipFlo_Click(object sender, EventArgs e)
        {
            string path1 = "D:\\DeBug1\\";   //待压缩的目录文件
            string path2 = "D:\\Debug2\\";   //压缩后存放目录文件
            //获取指定目录下所有文件和子文件名称(所有待压缩的文件)
            string[] files = Directory.GetFileSystemEntries(path1);
            ZipFloClass zc = new ZipFloClass();
            //遍历指定目录下文件路径
            foreach (string file in files)
            {
                //截取文件路径的文件名
                var filename = file.Substring(file.LastIndexOf("\\") + 1);
                //调用压缩方法(参数1:待压缩的文件目录,参数2:压缩后的文件目录(包含后缀))
                zc.ZipFile(path1 + filename, path2 + filename + ".zip");
            }
        }
 
        ///
        /// 批量解压事件
        ///
        ///
        ///
        private void btnBatchUnZipFlo_Click(object sender, EventArgs e)
        {
            string msg = "";
            string path2 = "D:\\Debug2\\";
            string path3 = "D:\\Debug3\\";
            //获取指定目录下所有文件和子文件名称(所有待解压的压缩文件)
            string[] files = Directory.GetFileSystemEntries(path2);
            UnZipFloClass uzc = new UnZipFloClass();
            //遍历所有压缩文件路径
            foreach (string file in files)
            {
                //获取压缩包名称(包括后缀名)
                var filename  = file.Substring(file.LastIndexOf("\\") + 1);
                //得到压缩包名称(没有后缀)
                filename = filename.Substring(0, filename.LastIndexOf("."));
                //判断解压的路径是否存在
                if (!Directory.Exists(path3 + filename))
                {
                    //没有,则创建这个路径
                    Directory.CreateDirectory(path3 + filename);
                }
                //调用解压方法(参数1:待解压的压缩文件路径(带后缀名),参数2:解压后存放的文件路径,参数3:返工是否解压成功)
                uzc.unZipFile(file, path3 + filename, ref msg);
            }
            MessageBox.Show("批量解压成功");
        }
    }
}


3.3) 物理路径创建3个文件,Dubug1,Dubug2,Dubug3



3、测试结果界面

3.1)demo 程序的界面



3.2)批量压缩/解压文件视图



3.3)批量压缩的结果视图



3.4) 批量解压的结果视图


三、demo源码下载

下载demo附件:ZipCompressTest.zip

参考资料来源:http://www.cnblogs.com/zfanlong1314/p/4202695.html#commentform


该文章在 2021/3/8 10:42:12 编辑过

全部评论1

admin
2021年3月8日 10:46
 public static void UnZip(string TargetFile, string fileDir)
     {
         try
         {
             using (ZipInputStream s = new ZipInputStream(File.OpenRead(TargetFile.Trim())))
             {
                 ZipEntry theEntry;
                 Directory.CreateDirectory(fileDir);
                 while ((theEntry = s.GetNextEntry()) != null)
                 {
                     var dir = Path.GetDirectoryName(theEntry.Name);
                     if (!string.IsNullOrWhiteSpace(dir))
                         Directory.CreateDirectory(fileDir + "\\" + dir);
                     if (!theEntry.IsDirectory)
                         CreateFile(s, fileDir + "\\" + theEntry.Name);
                 }
             }
         }
         catch (Exception ex)
         {
             LogHelper.Error($"解压文件{fileDir}到{TargetFile}时失败", ex);
         }
     }
 
 
private static void CreateFile(ZipInputStream s, string fileName)
     {
         using (FileStream streamWriter = File.Create(fileName))
         {
             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;
                 }
             }
         }
     }

楼主解压那段写的过于复杂 其实只需要文件夹创建文件夹,文件创建文件就好了

该评论在 2021/3/8 10:46:59 编辑过
关键字查询
相关文章
正在查询...
点晴ERP是一款针对中小制造业的专业生产管理软件系统,系统成熟度和易用性得到了国内大量中小企业的青睐。
点晴PMS码头管理系统主要针对港口码头集装箱与散货日常运作、调度、堆场、车队、财务费用、相关报表等业务管理,结合码头的业务特点,围绕调度、堆场作业而开发的。集技术的先进性、管理的有效性于一体,是物流码头及其他港口类企业的高效ERP管理信息系统。
点晴WMS仓储管理系统提供了货物产品管理,销售管理,采购管理,仓储管理,仓库管理,保质期管理,货位管理,库位管理,生产管理,WMS管理系统,标签打印,条形码,二维码管理,批号管理软件。
点晴免费OA是一款软件和通用服务都免费,不限功能、不限时间、不限用户的免费OA协同办公管理系统。
Copyright 2010-2024 ClickSun All Rights Reserved