DotNetZip "замерзает" на время распаковки, но нужно передавать инфу для прогрессбара - C#
Формулировка задачи:
Прошу помощи в том, как правильно выполнить распаковку с отображением хода процесса на прогрессбаре.
Использую Ionic.Zip.dll (DotNetZip).
Главный поток "замораживается" и я вижу сразу событие: Reading_Completed
Я так понимаю, нужен некий асинхронный запуск.
Может что в опциях еще нужно дописать - в доках это описано в разделе:
References -> Ionic.zip Namespace -> Read Options Class
Тестовый проект с библиотекой приложил.
P.S. Оф. документация есть в файле и еще доп. по ссылке.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using Ionic.Zip;
namespace ZipTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void ReadProgress1(object sender, ReadProgressEventArgs e)
{
labelPerc.Text = e.EventType.ToString();
//MessageBox.Show(e.EventType.ToString());
switch (e.EventType)
{
case ZipProgressEventType.Reading_ArchiveBytesRead:
int percent = Convert.ToInt32(e.BytesTransferred / e.TotalBytesToTransfer * 100);
if (progressBar1.Value != percent)
progressBar1.Value = percent;
//labelPerc.Text = percent.ToString();
break;
case ZipProgressEventType.Reading_Completed:
// Откроем целевую папку
break;
}
}
private void button1_Click(object sender, EventArgs e)
{
string FileNameFull = "D:\\temp\\MyJoe.zip";
string FolderNameFull = "D:\\temp\\Joe";
// Очищаем целевую папку
if (Directory.Exists(FolderNameFull))
{
/*
DirectoryInfo dirInfo = new DirectoryInfo(FolderNameFull);
foreach (FileInfo fil in dirInfo.GetFiles()) // Не буду использовать - метод нерекурсивен, а файлы - глубже
{
fil.Delete();
}
*/
Directory.Delete(FolderNameFull,true); //true - если директория не пуста (удалит и файлы, и папки)
Directory.CreateDirectory(FolderNameFull);
}
try
{
var options = new ReadOptions {
Encoding = Encoding.GetEncoding(866),
ReadProgress = ReadProgress1
};
using (ZipFile zip = ZipFile.Read(FileNameFull, options))
{
// This call to ExtractAll() assumes:
// - none of the entries are password-protected.
// - want to extract all entries to current working directory
// - none of the files in the zip already exist in the directory;
// if they do, the method will throw.
zip.ExtractAll(FolderNameFull);
}
//Откроем целевую папку
Process.Start(FolderNameFull);
}
catch (Exception ex)
{
MessageBox.Show(ex.Source + "\n" + ex.Message);
}
}
}
}Решение задачи: «DotNetZip "замерзает" на время распаковки, но нужно передавать инфу для прогрессбара»
textual
Листинг программы
private void ReadProgress1(object sender, ReadProgressEventArgs e)
{
Thread thread = new Thread(() => labelPerc.Invoke(new Action<Label>(l =>
{
l.Text = e.EventType.ToString();
} ) ) );
thread.Start();
thread.Abort();
labelPerc.Text = e.EventType.ToString();
switch (e.EventType)
{
case ZipProgressEventType.Reading_ArchiveBytesRead:
int percent = Convert.ToInt32(e.BytesTransferred / e.TotalBytesToTransfer * 100);
if (progressBar1.Value != percent)
progressBar1.Value = percent;
break;
case ZipProgressEventType.Reading_Completed:
// Откроем целевую папку
break;
}
}