dav*_*oxy 4 c# zip backgroundworker winforms dotnetzip
我有以下代码:
public void extractZipFile()
{
if (!System.IO.Directory.Exists(extractDirectory))
System.IO.Directory.CreateDirectory(extractDirectory);
BackgroundWorker worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.ProgressChanged += (o, e) =>
{
progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage);
};
lblExtracting.Text = "Extracting...";
worker.DoWork += (o, e) =>
{
using (ZipFile zip = ZipFile.Read(zipFile))
{
int step = Convert.ToInt32(zip.Count / 100.0);
int percentComplete = 0;
foreach (ZipEntry file in zip)
{
file.Extract(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\XBMC Library Importer\\XBMC_Files", ExtractExistingFileAction.OverwriteSilently);
percentComplete += step; //When I comment this out I don't get an exception
worker.ReportProgress(percentComplete);
}
}
};
worker.RunWorkerAsync();
}
Run Code Online (Sandbox Code Playgroud)
我不明白为什么该语句percentComplete += step;会导致错误 ( Exception has been thrown by the target of an invocation.)。
我怎么能解决这个问题?
另外,有人知道MessageBox.Show()提取完成后如何显示消息框 ( ) 吗?
任何帮助,将不胜感激。
您需要查看异常的 InnerException 属性以了解 TargetInvocationException 的原因。
粗略地猜测一下:您错误地计算了step的值。它应该是 100.0 / zip.Count。也应该是双。因此,当 .zip 文件包含超过 100 个文件时,您将面临将进度增加超过 100 的风险。当您将该值分配给 ProgressBar.Value 时,这会爆炸。您应该已经注意到进度条在小型档案中也表现不佳,根本没有增加。
调试此类难以捉摸的错误的一个好方法是调试 + 异常,勾选 CLR 异常的抛出复选框。当抛出异常时,调试器现在将停止。