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

c#
2312
2024/6/23 14:17:24
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在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显示压缩完成的消息。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c#中怎么用foreach循环遍历数组