前言

本篇主要记录: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/

  本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

最新文章

  1. 判断一个值是否为null或者undefined
  2. vim实用技巧
  3. OC开发中运用到的枚举
  4. 共享锁(S锁)和排它锁(X锁)
  5. iOS 抖动动画
  6. javascripct字符串
  7. PL/SQL学习(一)
  8. C# winform 导出导入Excel/Doc 完整实例教程[网上看到的]
  9. 怎样配置nginx同一时候执行不同版本号的php-fpm
  10. transfer.sh:通过命令行简单的创建文件分享
  11. pdf can&#39;t copy text 无法复制文字
  12. 使用maven命令进行打包,部署项目到远程仓库
  13. Service和Thread的关系
  14. [原创]spring及springmvc精简版--IOC
  15. shell之dialog提示窗口
  16. 《SQL Server 监控和诊断》
  17. CodeForces - 762E:Radio stations (CDQ分治||排序二分)
  18. (转) [C++]我再也不想在任何头文件中看到using namespace xxx这种句子了(译)
  19. PTA 08-图8 How Long Does It Take (25分)
  20. Oracle 数据库有五个必需的后台进程,DBWR,LGWR,CKPT,SMON,PMON

热门文章

  1. 用Python代码写的计算器
  2. 反转字符串中的单词 III
  3. 5面终于拿到了字节跳动offer! 鬼知道我经历了啥...
  4. 2019年百度最新Java工程师面试题
  5. Python 爬虫从入门到进阶之路(一)
  6. C#中类的修饰符
  7. Dynamics 365 CE Update消息PostOperation阶段Image的尝试
  8. [转]VB.net中 excel 的range方法
  9. Cesium专栏-地形开挖(附源码下载)
  10. 由导入paramkio包失败,而pip list又能查到此包,而引出的:离线安装python第三方库的实用方法:解决公司内网,服务器/电脑不能上网却需要安装python三方库问题(下:Linux环境中)