在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
顯示壓縮完成的消息。