Exemplo n.º 1
0
        /// <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);
            }
        }
Exemplo n.º 2
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="e"></param>
 protected virtual void OnWebOperationProgress(AsyncWebOperationsProgressArgs e)
 {
     WebOperationProgress?.Invoke(this, e);
 }