【问题标题】:Create progress bar for download zip为下载 zip 创建进度条
【发布时间】:2014-09-08 10:19:46
【问题描述】:

当用户下载 zip 或相同的文件时,我想在背景进度中创建一个进度条。这是我的代码:

    private void DoSincroFit()
    {
        HttpWebRequest request = HttpWebRequest.CreateHttp(url);

        //Add headers to request
        request.Headers["Type"] = "sincrofit";
        request.Headers["Device"] = "1";
        request.Headers["Version"] = "0.000";
        request.Headers["Os"] = "WindowsPhone";

        request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
    }

    public async void playResponseAsync(IAsyncResult asyncResult)
    {
        //Declaration of variables
        HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;

        try
        {
            string fileName = "sincrofit.rar";

            using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
            {
                byte[] buffer = new byte[1024];

                var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);

                using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                {
                    using (var outputStream = writeStream.GetOutputStreamAt(0))
                    {
                        using (var dataWriter = new DataWriter(outputStream))
                        {
                            using (Stream input = webResponse.GetResponseStream())
                            {
                                var totalSize = 0;
                                for (int size = input.Read(buffer, 0, buffer.Length); size > 0; size = input.Read(buffer, 0, buffer.Length))
                                {
                                    dataWriter.WriteBytes(buffer);
                                    totalSize += size;    //get the progress of download

                                    //I think the progress bar going here!
                                }
                                await dataWriter.StoreAsync();
                                await outputStream.FlushAsync();
                                dataWriter.DetachStream();
                            }
                        }
                    }
                }

            }
        }
        catch
        {
            CoreDispatcher dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
            dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
            {
                //Declaration of variables
                SMethods.Message_Dialog("Download has stopped!", "Error");
            });
        }
    }

这是调用后台方法的方法

    public async Task<string> doSync(ProgressBar bar)
    {
        //Declaration of variables
        string response = await DoRequest("CHECK", "1", "0.000", "WindowsPhone");
        pBar = bar;

        //When is 1, the checkConnection will connect
        if (response == "1")
        {
            response = response + "," + await DoRequest("SIZEFIT", "1", "0.000", "WindowsPhone");

            DoSincroFit();
            response += "," + await DoRequest("DELSINC", "1", "0.000", "WindowsPhone");

            return response;
        }

        return "0,0,0";
    }

当这是一个外部类时,如何创建进度条?没错,doSync 和 DoSincroFit 属于 Sync.cs,而我的 UI 是 MyPage.Xaml.cs。

提前致谢!

【问题讨论】:

    标签: c# windows windows-phone-8 progress-bar


    【解决方案1】:

    如果您使用 MVVM,您可能会创建在更改时通知的属性。然后,您对 UI 表示一无所知的外部代码只会更新这些属性。

    然后,在您的 UI 代码中,您将控件绑定到这些属性。

    在不了解您的应用程序的情况下,我无法在此提供任何具体内容。

    【讨论】:

      【解决方案2】:

      我终于可以解决这个问题了!我的进度条现在可以工作了!

          private void DoSincroFit()
          {
              HttpWebRequest request = HttpWebRequest.CreateHttp(url);
      
              //Add headers to request
              request.Headers["Type"] = "sincrofit";
              request.Headers["Device"] = "1";
              request.Headers["Version"] = "0.000";
              request.Headers["Os"] = "WindowsPhone";
      
              //Windows Cache Problems
              request.Headers["Cache-Control"] = "no-cache";
              request.Headers["Pragma"] = "no-cache";
      
              dispatcher = CoreWindow.GetForCurrentThread().Dispatcher;
              request.BeginGetResponse(new AsyncCallback(playResponseAsync), request);
          }
      
          public async void playResponseAsync(IAsyncResult asyncResult)
          {
              //Declaration of variables
              HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
      
              try
              {
                  //For download file  with stream
                  string fileName = "sincrofit.rar";
      
                  using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult))
                  {
                      byte[] buffer = new byte[1];
      
                      //For acces Local folder of phone device
                      var newZipFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
      
                      //Progress bar and their update
                      using (var writeStream = await newZipFile.OpenAsync(FileAccessMode.ReadWrite))
                      {
                          using (var outputStream = writeStream.GetOutputStreamAt(0))
                          {
                              using (var dataWriter = new DataWriter(outputStream))
                              {
                                  using (Stream input = webResponse.GetResponseStream())
                                  {
                                      var totalSize = 0;
                                      int read;
      
                                      uint zeroUint = Convert.ToUInt32(0);
                                      uint readUint;
      
                                      while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                                      {
                                          totalSize += read; 
      
                                          await dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                                          {
                                              //Declaration of variables
                                              pBar.Value = totalSize * 100 / sizeFit;
                                          });
      
                                          readUint = Convert.ToUInt32(read);
                                          IBuffer ibuffer = buffer.AsBuffer();
                                          dataWriter.WriteBuffer(ibuffer, zeroUint, readUint);
                                      }
      
                                      await dataWriter.StoreAsync();
                                      await outputStream.FlushAsync();
                                      dataWriter.DetachStream();
                                  }
                              }
                          }
                      }
      
                  }
              }
              catch
              {
                  //For control errors stopped progress bar
                  dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                  {
                      //Declaration of variables
                      SMethods.Message_Dialog("Download has stopped!", "Error");
                  });
              }
          }
      

      这是一个测试进度条,但如果你需要下载一个大的 zip,那么使用 1024 或相同的缓冲区...因为 1 字节可能很糟糕!谢谢大家! :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多