C# : How to report progress while creating a zip f

2019-01-26 19:53发布

Update: Got it working updated my working code

Here is what I have so far

 private async void ZipIt(string src, string dest)
    {
        await Task.Run(() =>
        {
            using (var zipFile = new ZipFile())
            {
                // add content to zip here 
                zipFile.AddDirectory(src);
                zipFile.SaveProgress +=
                    (o, args) =>
                    {
                        var percentage = (int)(1.0d / args.TotalBytesToTransfer * args.BytesTransferred * 100.0d);
                        // report your progress
                        pbCurrentFile.Dispatcher.Invoke(
                            System.Windows.Threading.DispatcherPriority.Normal,
                            new Action(
                            delegate()
                            {

                                pbCurrentFile.Value = percentage;
                            }
                            ));
                    };
                zipFile.Save(dest);
            }
        });
    }

I need to figure out how to update my progress bar but not sure if I am on the right track I have searched around and found many examples for windows forms and vb.net but nothing for wpf c# was wondering if anyone could help.

1条回答
一纸荒年 Trace。
2楼-- · 2019-01-26 20:44

I guess you are using DotNetZip ?

There are numerous issue in the code you've shown:

  • you don't call ReportProgress in DoWork so how do you expect to get the progress ?
  • even if you did so the problem is with zip.Save() you wouldn't get a progress (beside 100%) because it would not return unless it is finished.

Solution

Use tasks and SaveProgress event instead :

private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
    await Task.Run(() =>
    {
        using (var zipFile = new ZipFile())
        {
            // add content to zip here 
            zipFile.SaveProgress +=
                (o, args) =>
                {
                    var percentage = (int) (1.0d/args.TotalBytesToTransfer*args.BytesTransferred*100.0d);
                    // report your progress
                };
            zipFile.Save();
        }
    });
}

Doing this way, your UI will not freeze and you will get a periodic report of the progress.

Always prefer Tasks over BackgroundWorker since it's official approach to use now.

查看更多
登录 后发表回答