一、前言
本篇内容
本篇主要记录:VS2019 WinForm桌面应用程序的可视化编程。
通过调用SharpZipLib,实现文件的简单压缩和解压缩功能。
本篇目的
- 介绍调用SharpZipLib的方法(使用Nuget)
- 展现可视化编程制作窗体应用的步骤
- 给出Zip压缩解压应用在C#的具体实现
开发环境
- 操作系统: Windows 10 X64
- SDK:NET Framework 4.7.2
- IDE:Visual Studio 2019
二、Nuget的使用
Nuget是一个.NET平台下的开源的项目,它是Visual Studio的扩展。在使用Visual Studio开发基于.NET Framework的应用时,Nuget能把在项目中添加、移除和更新引用的工作变得更加快捷方便。 NuGet能更方便地把一些dll和文件(如jquery)添加到项目中,而不需要从文件中复制拷贝。说简单点,就是Nuget可以自动管理.NET项目依赖关系,但是项目要打包成Nuget包。vs2017可以直接发布生成Nuget包。Nuget包放在自已的Nuget服务器上,或者官方的Nuget服务器上。
项目中引用Nuget包
路径为:打开项目->工具->NuGet包管理器->管理解决方案的NuGet程序包
打开NuGet解决方案界面后,在浏览界面搜索SharpCompress,勾选后进行安装,等待安装成功
安装成功后即可在程序中使用包体内容了
三、建造可视化窗体
###搭建WinForm窗体界面
添加必要的控件,这里主要应用到Panel、Label、TextBox、RadioButton和Button,如下图
搭建的方法是通过工具箱选择需要的控件进行添加
工具箱如下图
选中需要的控件进行拖拽即可
四、代码实现
1.RadioButton选择
进行窗体的更改
private void ZipRadio_CheckedChanged(object sender, EventArgs e)
{
this.ToButton.Text = "压缩";
this.label2.Text = "压缩到";
}
private void UnZipRadio_CheckedChanged(object sender, EventArgs e)
{
this.ToButton.Text = "解压";
this.label2.Text = "解压到";
}
2.压缩函数代码
创建了类ZipClass用于放置具体压缩解压缩的实现
以下为类函数
static string Last;//需要压缩的文件夹前缀地址
/// <summary>
/// 创建压缩文件夹并进行压缩
/// </summary>
/// <param name="folderToZip">要压缩的文件夹路径,即源目录</param>
/// <param name="TartgetFile">压缩后输出的位置</param>
/// <returns></returns>
public static bool ToZip(string folderToZip, string TartgetFile)
{
bool result=false;
Directory.CreateDirectory(Path.GetDirectoryName(TartgetFile));
using (ZipOutputStream ZipStream = new ZipOutputStream(File.Create(TartgetFile)))
{
ZipStream.SetLevel(9);//设置压缩级别为6
Last = Path.GetDirectoryName(folderToZip);
result = Compress(folderToZip, ZipStream);
ZipStream.Finish();//压缩完成
ZipStream.Close();//关闭压缩包
}
return result;
}
/// <summary>
/// 具体压缩方法
/// </summary>
/// <param name="FolderToZip">要压缩的文件夹路径,即源目录</param>
/// <param name="ZipStream">ZipOutputStream对象</param>
/// <returns></returns>
public static bool Compress(string FolderToZip, ZipOutputStream ZipStream)
{
bool result = true;
string[] filenames = Directory.GetFileSystemEntries(FolderToZip);//获取文件夹内所有文件名(包括子文件夹)
foreach (string file in filenames)//进行遍历
{
if (Directory.Exists(file))//如果存在子文件夹
{
Compress(file, ZipStream); //递归压缩子文件夹
}
else//不是子文件夹而是文件
{//直接进行压缩操作
using (FileStream fs = File.OpenRead(file))
{
byte[] buffer = new byte[4 * 1024]; //缓冲区,每次操作大小
ZipEntry entry = new ZipEntry(file.Replace(Last, string.Empty)); //此处去掉盘符,创建压缩包内的文件
entry.DateTime = DateTime.Now;//文件创建时间
ZipStream.PutNextEntry(entry);//将文件写入压缩包
int sourceBytes;
do
{
sourceBytes = fs.Read(buffer, 0, buffer.Length);//读取文件内容(1次读4M,写4M)
ZipStream.Write(buffer, 0, sourceBytes);//将文件内容写入压缩包中相应的文件
} while (sourceBytes > 0);//一次读取没写完就继续写
}
}
}
return result;
}
3.解压缩函数代码
/// <summary>
/// 解压缩
/// </summary>
/// <param name="sourceFile">源文件</param>
/// <param name="targetPath">目标路经</param>
public static bool Decompress(string sourceFile, string targetPath)
{
if (!File.Exists(sourceFile))//找到需要解压缩的文件
{
throw new FileNotFoundException(string.Format("未能找到文件 '{0}' ", sourceFile));
}
if (!Directory.Exists(targetPath))//创建解压缩到的文件夹
{
Directory.CreateDirectory(targetPath);
}
using (ZipInputStream ZipInStream = new ZipInputStream(File.OpenRead(sourceFile)))//创建ZipInputStream对象
{
ZipEntry theEntry;
while ((theEntry = ZipInStream.GetNextEntry()) != null)//进行遍历
{
string directorName = Path.Combine(targetPath, Path.GetDirectoryName(theEntry.Name));
string fileName = Path.Combine(directorName, Path.GetFileName(theEntry.Name));
// 创建目录
if (directorName.Length > 0)
{
Directory.CreateDirectory(directorName);
}
if (fileName != string.Empty)
{
using (FileStream streamWriter = File.Create(fileName))
{
int size = 4096;
byte[] data = new byte[4 * 1024];
while (true)//进行解压
{
size = ZipInStream.Read(data, 0, data.Length);
if (size > 0)
{
streamWriter.Write(data, 0, size);
}
else break;
}
}
}
}
}
return true;
}
4.Button进行文件操作
private void FromButtom_Click(object sender, EventArgs e)
{
if(this.ZipRadio.Checked)
{
FolderBrowserDialog folderDialog = new FolderBrowserDialog();
folderDialog.Description = "选择你要压缩的文件";
folderDialog.RootFolder = Environment.SpecialFolder.Desktop;
if (folderDialog.ShowDialog() == DialogResult.OK)
{
this.FromTextBox.Text = folderDialog.SelectedPath;
}
}
else if(this.UnZipRadio.Checked)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "选择你要解压缩的文件";
fileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if (fileDialog.ShowDialog() == DialogResult.OK)
{
this.FromTextBox.Text = fileDialog.FileName;
}
}
}
private void ToButton_Click(object sender, EventArgs e)
{
if (this.ZipRadio.Checked)
{
try
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "选择你要压缩到的位置";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
this.ToTextBox.Text = fileDialog.FileName;//选择位置
}
string FileFrom = this.FromTextBox.Text;
string TartgetFile = this.ToTextBox.Text + ".zip";
bool flag = ZipClass.ToZip(FileFrom, TartgetFile);
if (flag)
{
MessageBox.Show(this, "压缩成功!", "Info", MessageBoxButtons.OK);
}
else
{
MessageBox.Show(this, "压缩失败", "Error", MessageBoxButtons.OK);
}
}
catch (Exception ex)
{
MessageBox.Show("压缩失败, Err info[" + ex.Message + "]", "Error");
}
}
else if (this.UnZipRadio.Checked)
{
try
{
SaveFileDialog fileDialog = new SaveFileDialog();
fileDialog.Title = "选择你要解压缩到的位置";
if (fileDialog.ShowDialog() == DialogResult.OK)
{
this.ToTextBox.Text = fileDialog.FileName;//选择位置
}
string FileFrom = this.FromTextBox.Text;
string TartgetFile = this.ToTextBox.Text ;
bool flag = ZipClass.Decompress(FileFrom, TartgetFile);
if (flag)
{
MessageBox.Show(this, "解压缩成功!", "Info", MessageBoxButtons.OK);
}
else
{
MessageBox.Show(this, "解压缩失败", "Error", MessageBoxButtons.OK);
}
}
catch (Exception ex)
{
MessageBox.Show("解压缩失败, Err info[" + ex.Message + "]", "Error");
}
}
}
五、参考文献等
###本篇参考了以下文章
VS(Visual Studio)中Nuget的使用 https://www.cjavapy.com/article/21/
SharpZipLib 文件/文件夹压缩 https://www.cnblogs.com/kissdodog/p/3525295.html
使用SharpZipLib实现zip压缩 https://www.cnblogs.com/tuyile006/archive/2008/04/25/1170894.html
感谢阅读!