C# - WinFrm应用程序调用SharpZipLib实现文件的压缩和解压缩
前言
本篇主要记录:VS2019 WinFrm桌面应用程序调用SharpZipLib,实现文件的简单压缩和解压缩功能。
SharpZipLib 开源地址戳这里。
准备工作
搭建WinFrm前台界面
添加必要的控件,这里主要应用到GroupBox、Label、TextBox、CheckBox和Button,如下图
核心代码
构造ZipHelper类
代码如下:
using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace ZipUnzip
{
class ZipHelper
{
private string rootPath = string.Empty; #region 压缩 /// <summary>
/// 递归压缩文件夹的内部方法
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipStream">压缩输出流</param>
/// <param name="parentFolderName">此文件夹的上级文件夹</param>
/// <returns></returns>
private bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
{
bool result = true;
string[] folders, files;
ZipEntry ent = null;
FileStream fs = null;
Crc32 crc = new Crc32(); try
{
string entName = folderToZip.Replace(this.rootPath, string.Empty) + "/";
//Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/")
ent = new ZipEntry(entName);
zipStream.PutNextEntry(ent);
zipStream.Flush(); files = Directory.GetFiles(folderToZip);
foreach (string file in files)
{
fs = File.OpenRead(file); byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
ent = new ZipEntry(entName + Path.GetFileName(file));
ent.DateTime = DateTime.Now;
ent.Size = fs.Length; fs.Close(); crc.Reset();
crc.Update(buffer); ent.Crc = crc.Value;
zipStream.PutNextEntry(ent);
zipStream.Write(buffer, , buffer.Length);
} }
catch
{
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect();
} folders = Directory.GetDirectories(folderToZip);
foreach (string folder in folders)
if (!ZipDirectory(folder, zipStream, folderToZip))
return false; return result;
} /// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <param name="password">密码</param>
/// <returns>是否压缩成功</returns>
public bool ZipDirectory(string folderToZip, string zipedFile, string password)
{
bool result = false;
if (!Directory.Exists(folderToZip))
return result; ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
zipStream.SetLevel();
if (!string.IsNullOrEmpty(password)) zipStream.Password = password; result = ZipDirectory(folderToZip, zipStream, ""); zipStream.Finish();
zipStream.Close(); return result;
} /// <summary>
/// 压缩文件夹
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径</param>
/// <param name="zipedFile">压缩文件完整路径</param>
/// <returns>是否压缩成功</returns>
public bool ZipDirectory(string folderToZip, string zipedFile)
{
bool result = ZipDirectory(folderToZip, zipedFile, null);
return result;
} /// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public bool ZipFile(string fileToZip, string zipedFile, string password)
{
bool result = true;
ZipOutputStream zipStream = null;
FileStream fs = null;
ZipEntry ent = null; if (!File.Exists(fileToZip))
return false; try
{
fs = File.OpenRead(fileToZip);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, , buffer.Length);
fs.Close(); fs = File.Create(zipedFile);
zipStream = new ZipOutputStream(fs);
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
ent = new ZipEntry(Path.GetFileName(fileToZip));
zipStream.PutNextEntry(ent);
zipStream.SetLevel(); zipStream.Write(buffer, , buffer.Length); }
catch
{
result = false;
}
finally
{
if (zipStream != null)
{
zipStream.Finish();
zipStream.Close();
}
if (ent != null)
{
ent = null;
}
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
GC.Collect();
GC.Collect(); return result;
} /// <summary>
/// 压缩文件
/// </summary>
/// <param name="fileToZip">要压缩的文件全名</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public bool ZipFile(string fileToZip, string zipedFile)
{
bool result = ZipFile(fileToZip, zipedFile, null);
return result;
} /// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <param name="password">密码</param>
/// <returns>压缩结果</returns>
public bool Zip(string fileToZip, string zipedFile, string password)
{
bool result = false;
if (Directory.Exists(fileToZip))
{
this.rootPath = Path.GetDirectoryName(fileToZip);
result = ZipDirectory(fileToZip, zipedFile, password);
}
else if (File.Exists(fileToZip))
{
this.rootPath = Path.GetDirectoryName(fileToZip);
result = ZipFile(fileToZip, zipedFile, password);
}
return result;
} /// <summary>
/// 压缩文件或文件夹
/// </summary>
/// <param name="fileToZip">要压缩的路径</param>
/// <param name="zipedFile">压缩后的文件名</param>
/// <returns>压缩结果</returns>
public bool Zip(string fileToZip, string zipedFile)
{
bool result = Zip(fileToZip, zipedFile, null);
return result; } #endregion #region 解压 /// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <param name="password">密码</param>
/// <returns>解压结果</returns>
public bool UnZip(string fileToUnZip, string zipedFolder, string password)
{
bool result = true;
FileStream fs = null;
ZipInputStream zipStream = null;
ZipEntry ent = null;
string fileName; if (!File.Exists(fileToUnZip))
return false; if (!Directory.Exists(zipedFolder))
Directory.CreateDirectory(zipedFolder); try
{
zipStream = new ZipInputStream(File.OpenRead(fileToUnZip));
if (!string.IsNullOrEmpty(password)) zipStream.Password = password;
while ((ent = zipStream.GetNextEntry()) != null)
{
if (!string.IsNullOrEmpty(ent.Name))
{
fileName = Path.Combine(zipedFolder, ent.Name);
fileName = fileName.Replace('/', '\\');//change by Mr.HopeGi if (fileName.EndsWith("\\"))
{
Directory.CreateDirectory(fileName);
continue;
} fs = File.Create(fileName);
int size = ;
byte[] data = new byte[size];
while (true)
{
size = zipStream.Read(data, , data.Length);
if (size > )
fs.Write(data, , data.Length);
else
break;
}
}
}
}
catch
{
result = false;
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
if (zipStream != null)
{
zipStream.Close();
zipStream.Dispose();
}
if (ent != null)
{
ent = null;
}
GC.Collect();
GC.Collect();
}
return result;
} /// <summary>
/// 解压功能(解压压缩文件到指定目录)
/// </summary>
/// <param name="fileToUnZip">待解压的文件</param>
/// <param name="zipedFolder">指定解压目标目录</param>
/// <returns>解压结果</returns>
public bool UnZip(string fileToUnZip, string zipedFolder)
{
bool result = UnZip(fileToUnZip, zipedFolder, null);
return result;
} #endregion
}
}
主窗体代码如下:
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; namespace ZipUnzip
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
} /// <summary>
/// Unzip/Zip Operation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void chbZip_CheckedChanged(object sender, EventArgs e)
{
if (this.chbZip.Checked)
{
if (this.chbUnzip.Checked)
{
this.chbUnzip.Checked = false;
}
}
} /// <summary>
/// Unzip/Zip Operation
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void chbUnzip_CheckedChanged(object sender, EventArgs e)
{
if (this.chbUnzip.Checked)
{
if (this.chbZip.Checked)
{
this.chbZip.Checked = false;
}
}
} /// <summary>
/// Choose File Directory
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnChoose_Click(object sender, EventArgs e)
{
if (this.chbZip.Checked)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.Description = "Choose File Directory";
folderDialog.RootFolder = Environment.SpecialFolder.Desktop;
DialogResult dr = folderDialog.ShowDialog(this);
if (dr == DialogResult.OK)
{
this.txtSFP.Text = folderDialog.SelectedPath;
}
}
else if (this.chbUnzip.Checked)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Choose Zip Files";
fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DialogResult dr = fileDialog.ShowDialog(this);
if (dr == DialogResult.OK)
{
this.txtSFP.Text = fileDialog.FileName;
}
}
} /// <summary>
/// Zip/Unzip
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDo_Click(object sender, EventArgs e)
{
// Check
if ((!this.chbZip.Checked) & (!this.chbUnzip.Checked))
{
MessageBox.Show("Please choose operation type!", "Error");
return;
}
// Zip
if (this.chbZip.Checked)
{
try
{
string src = this.txtSFP.Text;
string dest = AppDomain.CurrentDomain.BaseDirectory + @"\zipfolder\ZIP" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".zip";
if (!Directory.Exists(Path.GetDirectoryName(dest)))
{
Directory.CreateDirectory(Path.GetDirectoryName(dest));
}
ZipHelper zipHelper = new ZipHelper();
bool flag = zipHelper.Zip(src, dest);
if (flag)
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "Save Zip Package";
fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
fileDialog.FileName = Path.GetFileName(dest);
if (fileDialog.ShowDialog() == DialogResult.OK)
{
File.Copy(dest, fileDialog.FileName, true);
this.txtDFP.Text = fileDialog.FileName;
}
MessageBox.Show(this, "Zip Success!", "Info", MessageBoxButtons.OK);
}
else
{
MessageBox.Show(this, "Zip Failed", "Error", MessageBoxButtons.OK);
}
}
catch (Exception ex)
{
MessageBox.Show("Zip Failed, Err info[" + ex.Message + "]", "Error");
} } // Unzip
if (this.chbUnzip.Checked)
{
try
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.Description = "Choose Unzip Directory";
folderDialog.RootFolder = Environment.SpecialFolder.Desktop;
DialogResult dr = folderDialog.ShowDialog(this);
if (dr == DialogResult.OK)
{
string destPath = folderDialog.SelectedPath + @"\" + Path.GetFileNameWithoutExtension(this.txtDFP.Text);
ZipHelper zipHelper = new ZipHelper();
zipHelper.UnZip(this.txtSFP.Text, destPath);
this.txtDFP.Text = destPath;
}
MessageBox.Show("Unzip Success!", "Info");
}
catch (Exception ex)
{
MessageBox.Show("Unzip Failed, Err info[" + ex.Message + "]", "Error");
} }
}
}
}
实现效果
作者:Jeremy.Wu
出处:https://www.cnblogs.com/jeremywucnblog/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
C# - WinFrm应用程序调用SharpZipLib实现文件的压缩和解压缩的更多相关文章
- c#Winform程序调用app.config文件配置数据库连接字符串 SQL Server文章目录 浅谈SQL Server中统计对于查询的影响 有关索引的DMV SQL Server中的执行引擎入门 【译】表变量和临时表的比较 对于表列数据类型选择的一点思考 SQL Server复制入门(一)----复制简介 操作系统中的进程与线程
c#Winform程序调用app.config文件配置数据库连接字符串 你新建winform项目的时候,会有一个app.config的配置文件,写在里面的<connectionStrings n ...
- C# - VS2019 WinFrm应用程序调用WebService服务
WinFrm应用程序调用WebService服务 关于WebService的创建.发布与部署等相关操作不再赘述,传送门如下:C# VS2019 WebService创建与发布,并部署到Windows ...
- 在C#中利用SharpZipLib进行文件的压缩和解压缩收藏
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net(http://www.icsharpcode.net/OpenSource/SharpZipL ...
- C#利用SharpZipLib进行文件的压缩和解压缩
我在做项目的时候需要将文件进行压缩和解压缩,于是就从http://www.icsharpcode.net下载了关于压缩和解压缩的源码,但是下载下来后,面对这么多的代码,一时不知如何下手.只好耐下心来, ...
- 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的生命周期和程序的生命周期
[源码下载] 重新想象 Windows 8 Store Apps (70) - 其它: 文件压缩和解压缩, 与 Windows 商店相关的操作, app 与 web, 几个 Core 的应用, 页面的 ...
- C# 利用ICSharpCode.SharpZipLib.dll 实现压缩和解压缩文件
我们 开发时经常会遇到需要压缩文件的需求,利用C#的开源组件ICSharpCode.SharpZipLib, 就可以很容易的实现压缩和解压缩功能. 压缩文件: /// <summary> ...
- iOS中使用ZipArchive压缩和解压缩文件-备
为什么我需要解压缩文件 有许多原因能解释为什么我要在工程中使用压缩和解压缩功能,下面是几个常见的原因: 苹果App Store的50M下载限制 苹 果公司出于流量的考虑,规定在非WIFI环境下,限制用 ...
- Java用ZIP格式压缩和解压缩文件
转载:java jdk实例宝典 感觉讲的非常好就转载在这保存! java.util.zip包实现了Zip格式相关的类库,使用格式zip格式压缩和解压缩文件的时候,须要导入该包. 使用zipoutput ...
- 使用commons-compress操作zip文件(压缩和解压缩)
http://www.cnblogs.com/luxh/archive/2012/06/28/2568758.html Apache Commons Compress是一个压缩.解压缩文件的类库. 可 ...
随机推荐
- mybatis基础 笔记
Mybatis依赖<!--测试--> <dependency> <groupId>junit</groupId> <artif ...
- BZOJ3894/LG4313 文理分科 新建点最小割
问题描述 BZOJ3894 LG4313 题解 显然一个人只能选文/理 -> 一个人只能属于文(S).理(T)集合中的一个 可以把选择文得到 \(art\) 的收益看做选择文失去 \(scien ...
- C语言程序设计100例之(24):数制转换
例24 数制转换 题目描述 请你编一程序实现两种不同进制之间的数据转换. 输入格式 共三行,第一行是一个正整数,表示需要转换的数的进制n(2≤n≤16),第二行是一个n进制数,若n>10则用 ...
- 【一起刷LeetCode】在未排序的数组中找到第 k 个最大的元素
题目描述 在未排序的数组中找到第 k 个最大的元素.请注意,你需要找的是数组排序后的第 k 个最大的元素,而不是第 k 个不同的元素. 示例 1: 输入: [3,2,1,5,6,4] 和 k = 2 ...
- MIT / BSD / Apache / LGPL / Mozilla / GPL 区别
自由度:MIT > BSD > Apache > LGPL > Mozilla > GPL
- 损失函数--KL散度与交叉熵
损失函数 在逻辑回归建立过程中,我们需要一个关于模型参数的可导函数,并且它能够以某种方式衡量模型的效果.这种函数称为损失函数(loss function). 损失函数越小,则模型的预测效果越优.所以我 ...
- JVM内存模型与类加载机制
一. java虚拟机的内存模型如图: 补习一下jvm内存模型中的各个组成部分 堆: 我们new出来的对象全部放在堆中,他是jvm所能够动态分配的最大的一块空间 优点: 内存动态分配,生命周期不必事先告 ...
- Mybatis1
一.MyBatis介绍 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis ...
- GO-切片拷贝以及赋值
一.拷贝 package main import "fmt" func main(){ //copy函数,把一个切片copy到另一个切片之上 var a [1000]int=[10 ...
- ORM和Mybatis
ORM框架 概述 在学习MyBatis之前,先来看看什么是ORM框架. ORM全称Object/Relation Mapping,对象/关系数据库映射,功能为完成对象的编程语言到关系数据库的映射,可以 ...