简体   繁体   English

C#:如何在创建zip文件时报告进度?

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

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. 我需要弄清楚如何更新进度条,但是不确定我是否走在正确的轨道上,发现了许多关于Windows窗体和vb.net的示例,但对于wpf c#却一无所知。

I guess you are using DotNetZip ? 我猜您在使用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 ? 您不会在DoWork调用ReportProgress ,那么您如何期望获得进度?
  • 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. 即使您这样做,问题也出在zip.Save()您将无法获得进度(100%旁),因为除非完成,否则进度不会返回。

Solution

Use tasks and SaveProgress event instead : 使用任务和SaveProgress事件代替:

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. 始终优先使用Tasks而不是BackgroundWorker因为它是现在可以使用的官方方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM