/// <summary> /// /// </summary> /// <param name="file"></param> /// <returns></returns> private string SetFilePath(WebOperationDownloadObject file) { if (!string.IsNullOrWhiteSpace(file.Filename)) { return(string.IsNullOrEmpty(Preferences.DownloadPath) ? new KnownFolder(KnownFolderType.Downloads).DefaultPath + "/" + file.Filename + file.Url.Segments.Last().Substring(file.Url.Segments.Last().LastIndexOf('.')) : Preferences.DownloadPath + "/" + file.Filename + file.Url.Segments.Last().Substring(file.Url.Segments.Last().LastIndexOf('.'))); } else { return(string.IsNullOrEmpty(Preferences.DownloadPath) ? new KnownFolder(KnownFolderType.Downloads).DefaultPath + "/" + file.Url.Segments.Last() : Preferences.DownloadPath + "/" + file.Url.Segments.Last()); } }
/// <summary> /// Downloads a document from a specified url. /// </summary> /// <param name="file">The object which holds the downloading file details.</param> public async void DownloadFileAsync(WebOperationDownloadObject file) { try { WebRequest = (HttpWebRequest)WebRequest.Create(file.Url); WebRequest.Proxy = Proxy; WebRequest.Method = WebRequestMethods.Http.Get; string filePath = SetFilePath(file); using (var response = (HttpWebResponse)await WebRequest.GetResponseAsync()) { long fileSize = response.ContentLength; byte[] buffer = new byte[fileSize]; using (var reader = response.GetResponseStream()) { using (var filestream = File.Create(filePath)) { WriteFileDetail(filePath, fileSize); int bytesRead; while (reader != null && (bytesRead = await reader.ReadAsync(buffer, 0, buffer.Length)) != 0) { while (WebOperationState == State.Paused) { await Task.Delay(1000); } await filestream.WriteAsync(buffer, 0, bytesRead); WebOperationProgress?.Invoke(this, new AsyncWebOperationsProgressArgs(fileSize, filestream.Length)); await filestream.FlushAsync(); } } } } WebOperationCompleted?.Invoke(this, new AsyncWebOperationsCompleteArgs()); } catch (WebException e) { if (e.Status == WebExceptionStatus.RequestCanceled) { WebOperationCompleted(this, new AsyncWebOperationsCompleteArgs(State.Stopped)); } } catch (Exception e) { MessageBox.Show("" + e.InnerException.Message); } }