I have the following code:

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();
}

I don't understand why the statement percentComplete += step; causes an error (Exception has been thrown by the target of an invocation.).

How could I fix this?

Also, does anybody knows how could I display a message box (MessageBox.Show()) when extraction is complete?

Any help would be appreciated.

有帮助吗?

解决方案

You'll need to look at the exception's InnerException property to know the cause of the TargetInvocationException.

Taking a rough guess at it: you calculate the value of step incorrectly. It should be 100.0 / zip.Count. Should be a double as well. So you'll risk incrementing progress past 100 when the .zip file contains more than 100 files. And that will bomb when you assign that value to ProgressBar.Value. You should have noticed the progress bar misbehaving as well on small archives, never incrementing at all.

A good way to debug elusive bugs like this is Debug + Exception, tick the Thrown checkbox for CLR exceptions. The debugger will now stop when the exception is thrown.

其他提示

 worker.ProgressChanged += (o, e) =>
    {

// looks like you are tying to update the GUI element from background thread and it is throwing exception. Try marshalling thread to GUI thread.

progbarExtract.Value = Convert.ToInt32(e.ProgressPercentage);
    };
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top