为下载zip创建进度条

时间:2014-09-08 10:19:46

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

我想在用户下载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。

提前致谢!

2 个答案:

答案 0 :(得分:1)

如果您使用的是MVVM,则可能会创建在更改时通知的属性。然后,您不应该对UI表示真正了解的外部代码只是更新这些属性。

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

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

答案 1 :(得分:0)

最后我可以解决这个问题!我的进度条现在可以正常工作!

    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个字节可能很糟糕!谢谢大家! :)