Asynchronous File Download with Progress Bar

后端 未结 4 1625
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 03:18

I am attempting to have a progress bar\'s progress change as the WebClient download progress changes. This code still downloads the file yet when I call s

4条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-29 03:59

     public class ProgressEventArgsEx
    {
        public int Percentage { get; set; }
        public string Text { get; set; }
    }
    public async static Task DownloadStraingAsyncronous(string url, IProgress progress)
    {
        WebClient c = new WebClient();
        byte[] buffer = new byte[1024];
        var bytes = 0;
        var all = String.Empty;
        using (var stream = await c.OpenReadTaskAsync(url))
        {
            int total = -1;
            Int32.TryParse(c.ResponseHeaders[HttpRequestHeader.ContentLength], out total);
            for (; ; )
            {
                int len = await stream.ReadAsync(buffer, 0, buffer.Length);
                if (len == 0)
                    break;
                string text = c.Encoding.GetString(buffer, 0, len);
    
                bytes += len;
                all += text;
                if (progress != null)
                {
                    var args = new ProgressEventArgsEx();
                    args.Percentage = (total <= 0 ? 0 : (100 * bytes) / total);
                    progress.Report(args);
                }
            }
        }
        return all;
    }
    // Sample
    private async void Bttn_Click(object sender, RoutedEventArgs e)
    {
        //construct Progress, passing ReportProgress as the Action 
        var progressIndicator = new Progress(ReportProgress);
        await TaskLoader.DownloadStraingAsyncronous(tbx.Text, progressIndicator);
    }
    private void ReportProgress(ProgressEventArgsEx args)
    {
        this.statusText.Text = args.Text + " " + args.Percentage;
    }
    

提交回复
热议问题