基本信息
源码名称:zip压缩、解压、进度条
源码大小:2.63M
文件格式:.zip
开发语言:C#
更新时间:2017-09-19
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 1 元 
   源码介绍


 BackgroundWorker worker = new BackgroundWorker();
        public Form1()
        {
            InitializeComponent();
            worker.WorkerSupportsCancellation = true;//是否支持异步取消
            worker.WorkerReportsProgress = true;//能否报告进度更新
            worker.DoWork = Worker_DoWork;
        }


        int value;
        private void button1_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            //saveFileDialog1.ShowDialog();
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Add(folderBrowser.SelectedPath);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFile = new SaveFileDialog();
            saveFile.Filter = "zip files(*.zip)|*.zip";
            if (saveFile.ShowDialog() == DialogResult.OK)
            {
                textBox1.Text = saveFile.FileName;
            }
        }

        private void button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                listBox1.Items.Add(openFile.FileName);
            }
        }

        private void compression_Click(object sender, EventArgs e)
        {
            value = 0;
            worker.RunWorkerAsync("compression");//会触发worker的DoWork事件
            ProgressFrom progress = new ProgressFrom(worker);
            progress.ShowDialog(this);
        }

        private void uncompression_Click(object sender, EventArgs e)
        {
            value = 0;
            worker.RunWorkerAsync("uncompression");
            ProgressFrom progress = new ProgressFrom(worker);//将worker给progress窗体
            progress.ShowDialog(this);
        }

        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();
                }
            }
        }
        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);//报告进度,和刚压缩完成的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);
                }
            }
        }
        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;
                            }
                        }
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog folderBrowser = new FolderBrowserDialog();
            if (folderBrowser.ShowDialog() == DialogResult.OK)
            {
               textBox2.Text= folderBrowser.SelectedPath;
            }
        }

    }