public static async Task DownloadFileTaskAsync(this WebClient client, string url, string filepath, CancellationToken cancellationToken, IProgress<DownloadDataProgress> progress) { using (var s = await client.OpenReadTaskAsync(url)) { long totalBytes = 0; Int64.TryParse(client.ResponseHeaders[HttpResponseHeader.ContentLength], out totalBytes); using (var fs = File.Open(filepath, FileMode.Create, FileAccess.Write, FileShare.Read)) { var cprogress = new Progress<StreamCopyProgress>(); cprogress.ProgressChanged += new EventHandler<StreamCopyProgress>((sender, e) => { var r = new DownloadDataProgress(e, totalBytes); r.UserState = e.UserState; progress.Report(r); }); await s.CopyToAsync(fs, cancellationToken, cprogress); } } }
public static async Task<byte[]> DownloadDataTaskAsync(this WebClient client, string url, CancellationToken cancellationToken, IProgress<DownloadDataProgress> progress) { using (var s = await client.OpenReadTaskAsync(url)) { long totalBytes = 0; Int64.TryParse(client.ResponseHeaders[HttpResponseHeader.ContentLength], out totalBytes); using (var mso = new MemoryStream()) { var cprogress = new Progress<StreamCopyProgress>(); cprogress.ProgressChanged += new EventHandler<StreamCopyProgress>((sender, e) => { var r = new DownloadDataProgress(e, totalBytes); r.UserState = e.UserState; progress.Report(r); }); await s.CopyToAsync(mso, cancellationToken, cprogress); return mso.ToArray(); } } }