static async Task DoDownload(Uri url, string targetFile, DownloadStatus status) { using (var httpClient = new HttpClient()) { httpClient.Timeout = WebRequestTimeout; Log.DebugLine("Calling GetAsync"); HttpResponseMessage resp = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); Log.DebugLine("GetAsync finished"); resp.EnsureSuccessStatusCode(); string dir = Path.GetDirectoryName(targetFile); CreateDirectory(dir); using (var fs = File.Open(targetFile, FileMode.Create, FileAccess.Write)) { using (var webStream = await resp.Content.ReadAsStreamAsync()) { status.Start(); WriteWithProgress(fs, webStream, status); } } } }
public static async Task <bool> Download(Uri url, string targetFile, DownloadStatus status) { if (url == null) { throw new ArgumentNullException(nameof(url)); } if (String.IsNullOrEmpty(targetFile)) { throw new ArgumentException("must not be null or empty", nameof(targetFile)); } if (status == null) { throw new ArgumentNullException(nameof(status)); } using (var httpClient = new HttpClient()) { httpClient.Timeout = WebRequestTimeout; HttpResponseMessage resp; try { Log.DebugLine("Calling GetAsync"); resp = await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); Log.DebugLine("GetAsync finished"); } catch (Exception ex) { Log.DebugLine($"Exception: {ex}"); throw; } resp.EnsureSuccessStatusCode(); string dir = Path.GetDirectoryName(targetFile); CreateDirectory(dir); using (var fs = File.Open(targetFile, FileMode.Create, FileAccess.Write)) { using (var webStream = await resp.Content.ReadAsStreamAsync()) { status.Start(); await DoDownload(fs, webStream, status); } } } return(true); }