C#:如何在创建一个zip文件报告进展情况? [英] C# : How to report progress while creating a zip file?

查看:166
本文介绍了C#:如何在创建一个zip文件报告进展情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:得到它的工作更新我的工作代码

Update: Got it working updated my working code

下面是我迄今为止

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



我需要弄清楚如何更新我的进度条,但不知道如果我我找遍了四周,发现窗户的形式和vb.net,但没有为WPF C#的例子很多想知道如果有人可以帮助在正确的轨道上。

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.

推荐答案

我猜你正在使用DotNetZip

有对你所显示的代码众多问题:

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


  • 您不叫的在ReportProgress 的DoWork 所以你怎么能指望获得的进展如何?

  • 即使你这样做的问题是与 zip.Save()你不会得到(旁边的100%)的进度,因为除非是完成了它不会再回来。

  • 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.

解决方案

使用任务和 SaveProgress 事件来代替:

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



做这样一来,你的UI不会冻结,您将获得进展情况的定期报告。

总是更喜欢的BackgroundWorker 任务,因为它的官方的方法现在使用。

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

这篇关于C#:如何在创建一个zip文件报告进展情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆