如,下图操作,任意选择要压缩的文件夹,文件,设置压缩后保存的文件,点压缩按钮
执行效果如下
执行完的test1.zip
压缩需要引用using ICSharpCode.SharpZipLib.Zip;
可在http://www.icsharpcode.net/opensource/sharpziplib/Default.aspx下载
首先看BackgroundWorker初始化的代码
BackgroundWorker worker = new BackgroundWorker();
public Form1()
{
InitializeComponent();
worker.WorkerSupportsCancellation = true;//是否支持异步取消
worker.WorkerReportsProgress = true;//能否报告进度更新
worker.DoWork += Worker_DoWork;
}
在压缩按钮的代码里主要是worker.RunWorkerAsync()和show进度条窗体
private void compression_Click(object sender, EventArgs e)
{
value = 0;//进度条的值
worker.RunWorkerAsync("compression");//会触发worker的DoWork事件
ProgressFrom progress = new ProgressFrom(worker);//将worker给progress窗体
progress.ShowDialog(this);
}
worker.RunWorkerAsync()会执行Worker_DoWork方法,压缩和解压都是BackgroundWorker在后台执行
private void Worker_DoWork(object sender, DoWorkEventArgs e)
{
if (e.Argument.ToString()== "compression")
{
try
{
//Create Zip File
ZipOutputStream zipStream = null;
using (zipStream = new ZipOutputStream(File.Create(textBox1.Text)))
{
zipStream.Password = "123";//压缩密码
zipStream.SetComment("版本1.0");//压缩文件描述
zipStream.SetLevel(6); //设置CompressionLevel,压缩比