C# : How to report progress while creating a zip file?

送分小仙女□ 提交于 2019-12-18 07:01:50

问题


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:


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.



来源:https://stackoverflow.com/questions/22976841/c-sharp-how-to-report-progress-while-creating-a-zip-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!