c#

C# Zip压缩进度条怎么添加

小樊
117
2024-07-13 14:17:24
栏目: 编程语言

在C#中实现Zip压缩进度条,可以通过使用System.IO.Compression.ZipArchive类来完成。以下是一个示例代码,其中通过使用System.IO.Compression.ZipArchive类来压缩文件,并通过Progress<T>类来实现进度条。

using System;
using System.IO;
using System.IO.Compression;
using System.Threading.Tasks;
using System.Net;
using System.Windows.Forms;

namespace ZipProgress
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private async void btnZip_Click(object sender, EventArgs e)
        {
            string zipPath = @"C:\Users\user\Desktop\test.zip";
            string[] filesToZip = new string[] { @"C:\Users\user\Desktop\file1.txt", @"C:\Users\user\Desktop\file2.txt" };

            progressBar1.Maximum = filesToZip.Length;
            IProgress<int> progress = new Progress<int>(value =>
            {
                progressBar1.Value = value;
            });

            await Task.Run(() =>
            {
                using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Create))
                {
                    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
                    {
                        for (int i = 0; i < filesToZip.Length; i++)
                        {
                            string fileToAdd = filesToZip[i];
                            ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(fileToAdd));
                            using (Stream entryStream = readmeEntry.Open())
                            using (Stream fileToCompress = File.OpenRead(fileToAdd))
                            {
                                fileToCompress.CopyTo(entryStream);
                            }

                            progress.Report(i + 1);
                        }
                    }
                }
            });

            MessageBox.Show("Zip compression complete!");
        }
    }
}

在上面的示例中,使用IProgress<int>接口来报告进度,并在压缩每个文件时更新进度条的值。最后,使用MessageBox显示压缩完成的消息。

0
看了该问题的人还看了