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是一个压缩.解压缩文件的类库. 可 ...
随机推荐
- [阅读笔记]EfficientDet
EfficientDet 文章阅读 Google的网络结构不错,总是会考虑计算性能的问题,从mobilenet v1到mobile net v2.这篇文章主要对近来的FPN结构进行了改进,实现了一种效 ...
- 微信小程序之POST请求
最近写自己的小项目时,遇到一个问题很头疼,几天了一直解决不了 背景: 前端调用java接口,存中文乱码 但是该接口所要存数据的表在B服务器同样的数据库里面,调用B服务器的接口存中文就没问题 起初以为是 ...
- 第二篇:C++画圆
安装GUI开发工具easyX #include <graphics.h>#include <Windows.h> int main(void) { initgraph(640, ...
- Unity ugui屏幕适配与世界坐标到ugui屏幕坐标的转换
我们知道,如今的移动端设备分辨率五花八门,而开发过程中往往只取一种分辨率作为设计参考,例如采用1920*1080分辨率作为参考分辨率. 选定了一种参考分辨率后,美术设计人员就会固定以这样的分辨率来设计 ...
- SpringCloud的入门学习之概念理解、Eureka服务注册与发现入门
1.微服务与微服务架构.微服务概念如下所示: 答:微服务强调的是服务的大小,它关注的是某一个点,是具体解决某一个问题.提供落地对应服务的一个服务应用,狭意的看,可以看作Eclipse里面的一个个微服务 ...
- 对象流,它们是一对高级流,负责即将java对象与字节之间在读写的过程中进行转换。 * java.io.ObjectOutputStream * java.io.ObjectInputStream
package seday06; import java.io.Serializable;import java.util.Arrays; /** * @author xingsir * 使用当前类来 ...
- SSM框架之Mybatis(5)数据库连接池及事务
Mybatis(5)数据库连接池及事务 1.Mybatis连接池 Mybatis 中也有连接池技术,但是它采用的是自己的连接池技术.在 Mybatis 的 SqlMapConfig.xml 配置文 ...
- sqlmap总结
转自:http://www.zerokeeper.com/web-security/sqlmap-usage-summary.html 0x01 需要了解 当给 sqlmap 这么一个 url 的时候 ...
- 记录:c#实现微信,支付宝扫码支付(一)
因为公司系统业务需要,这几天了解了一下微信和支付宝扫码支付的接口,并用c#实现了微信和支付宝扫码支付的功能. 微信支付分为6种支付模式:1.付款码支付,2.native支付,3.jsapi支付,4.a ...
- 【Gradle】Gradle插件
Gradle插件 插件的作用 把插件应用到项目中,插件会扩展项目的功能,帮助在项目构建过程中做很多事情. 1.可以添加任务到项目中,帮助完成测试.编译.打包等. 2.可以添加依赖配置到项目中,可以通过 ...