C#压缩解压(可任意选择多个文件夹,文件一起压缩);BackgroundWorker配合进度条的使用

如,下图操作,任意选择要压缩的文件夹,文件,设置压缩后保存的文件,点压缩按钮

这里写图片描述

执行效果如下

这里写图片描述

执行完的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,压缩比
                        foreach (string f in listBox1.Items)
                        {
                            ZipMultiFiles(f, zipStream);//压缩
                        }                     
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("压缩失败" + "\r\n" + ex.Message);
                }
                finally
                {
                    worker.CancelAsync();      //取消后台操作                          
                }
            }
            else
            {
                try
                {
                    ZipInputStream zipStream = null;
                    foreach (string f in listBox1.Items)
                    {
                        if (File.Exists(f))
                        {
                            using (zipStream = new ZipInputStream(File.OpenRead(f)))
                            {
                                zipStream.Password = "123";
                                UnZipMultiFiles(f, zipStream,textBox2.Text);
                            }
                        }
                    }                  
                }
                catch(Exception ex)
                {
                    MessageBox.Show("解压失败" + "\r\n" + ex.Message);
                }
                finally
                {
                    worker.CancelAsync();
                }
            }
        }

压缩ZipMultiFiles方法如下

        private void ZipMultiFiles(string file, ZipOutputStream zipStream, string lastName = "")
        {
            FileStream streamReader = null;
            if (File.Exists(file))      //是文件,压缩  
            {
                using (streamReader = File.OpenRead(file))
                {
                    //处理file,如果不处理,直接new ZipEntry(file)的话,压缩出来是全路径
                    //如C:\Users\RD\Desktop\image\001.xml,压缩包里就是C:\Users\RD\Desktop\image\001.xml
                    //如果处理为image\001.xml压缩出来就是image\001.xml(这样才跟用工具压缩的是一样的效果)
                    string path = Path.GetFileName(file);
                    if (lastName != "")
                    {
                        path = lastName + "\\" + path;
                    }
                    ZipEntry zipEntry = new ZipEntry(path);
                    zipEntry.DateTime = DateTime.Now;
                    zipEntry.Size = streamReader.Length;

                    zipStream.PutNextEntry(zipEntry);//压入
                    int sourceCount = 0;
                    byte[] buffer = new byte[4096 * 1024];
                    while ((sourceCount = streamReader.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        zipStream.Write(buffer, 0, sourceCount);
                        if (worker.WorkerReportsProgress)
                        {
                            if (value == 100)//因为不知道要压缩的总量有多大,所以这里简陋的让进度条从0-100循环
                            {
                                value = 0;
                            }
                            value += 1;
                            worker.ReportProgress(value);//报告进度,在progress窗体里响应
                        }
                        if (worker != null && worker.IsBusy)
                        {
                            if (worker.CancellationPending)
                            {
                                // update the entry size to avoid the ZipStream exception
                                zipEntry.Size = streamReader.Position;
                                break;
                            }
                        }
                    }
                    if (worker.WorkerReportsProgress)
                    {
                        worker.ReportProgress(value, file);
                    }
                    if (worker != null && worker.CancellationPending)
                    {
                        return;
                    }
                }
            }
            else//是文件夹,递归
            {
                string[] filesArray = Directory.GetFileSystemEntries(file);
                string folderName = Regex.Match(file, @"[^\/:*\?\”“\<>|,\\]*$").ToString();//获取最里一层文件夹
                if (lastName != "")
                {
                    folderName = lastName + "\\" + folderName;
                }
                if (filesArray.Length == 0)//如果是空文件夹
                {
                    ZipEntry zipEntry = new ZipEntry(folderName + "/");//加/才会当作文件夹来压缩
                    zipStream.PutNextEntry(zipEntry);
                }
                foreach (string f in filesArray)
                {
                    ZipMultiFiles(f, zipStream, folderName);
                }
            }
        }

这里再给出进度条窗体的代码,这里响应了ZipMultiFiles的worker.ReportProgress(),所以能看到开始给的图中效果

     public partial class ProgressFrom : Form
    {
        private BackgroundWorker backgroundWorker;
        public ProgressFrom(BackgroundWorker worker)
        {
            InitializeComponent();
            backgroundWorker = worker;
            backgroundWorker.ProgressChanged += BackgroundWorker_ProgressChanged;//响应 worker.ReportProgress();
            backgroundWorker.RunWorkerCompleted += BackgroundWorker_RunWorkerCompleted;//响应worker.CancelAsync();
        }

        private void BackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.Close();
        }
        private void BackgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            progressBar1.Value = e.ProgressPercentage;// e.ProgressPercentage接收ReportProgress的第一个参数
            if (e.UserState!=null)
            {
                string message = e.UserState.ToString() + "压缩完成\r\n";// e.UserState.ToString()接收ReportProgress的第二个参数
                textBox1.AppendText(message);
            }           
        }
    }

解压的方法UnZipMultiFiles为

 private void UnZipMultiFiles(string file, ZipInputStream zipStream,string unzippath)
        {
            ZipEntry theEntry;
            while ((theEntry = zipStream.GetNextEntry()) != null)
            {
                string fileName=Path.GetFileNameWithoutExtension(file);
                string entryName = theEntry.Name.Replace(":", "_");//如果路径里有盘符 如C: 解压后应为名为C_的文件夹来代表盘符
                string directoryName =Path.Combine( unzippath , fileName,entryName );
                //建立下面的目录和子目录  
                if (!Directory.Exists(Path.GetDirectoryName(directoryName)))
                {
                    Directory.CreateDirectory(Path.GetDirectoryName(directoryName));
                }
                string name =directoryName.Replace('/', '\\');//如果为空文件
                if (name.EndsWith("\\"))
                {
                    continue;
                }
                using (FileStream streamWriter = File.Create(directoryName))
                {
                    int sourceCount = 0;
                    byte[] buffer = new byte[4096 * 1024];
                    while ((sourceCount = zipStream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        streamWriter.Write(buffer, 0, sourceCount);
                        if (worker.WorkerReportsProgress)
                        {
                            if (value == 100)
                            {
                                value = 0;
                            }
                            value += 1;
                            worker.ReportProgress(value);
                        }
                        if (worker != null && worker.IsBusy)
                        {
                            if (worker.CancellationPending)
                            {
                                break;
                            }
                        }
                    }
                }
            }
        }

这里主要想试验压缩和BackgroundWorker,所有很多细节没有完善处理。

简单的压缩解压也可以用GZipStream

 using (FileStream intputStream = new FileStream("D:\\test.txt", FileMode.OpenOrCreate))
            {
                using (FileStream outputStream = new FileStream("D:\\test.zip", FileMode.OpenOrCreate, FileAccess.Write))
                {
                    using (GZipStream zipStream = new GZipStream(outputStream, CompressionMode.Compress))
                    {
                        byte[] byts = new byte[1024];
                        int len = 0;
                        while((len= intputStream.Read(byts,0,byts.Length))>0)
                        {
                            zipStream.Write(byts, 0, byts.Length);
                        }                     
                    }
                }
            }

下载源码:https://pan.baidu.com/s/1jIBT73C

猜你喜欢

转载自blog.csdn.net/m0_38110784/article/details/74987161