Beispiel #1
0
        /// <summary>
        /// Tải 1 tập tin (hỗ trợ thông tin dung lượng tải)
        /// </summary>
        /// <param name="URL">Liên kết của tập tin</param>
        /// <param name="filename">Đương dẫn lưu tập tin</param>
        /// <returns></returns>
        public async Task <bool> DownloadFileWithProgressAsync(string URL, string filename)
        {
            FileStream fs = default;

            try {
                _currentFile = GetFileName(URL);
                WebRequest wRemote         = default;
                var        bBuffer         = new byte[257];
                var        iBytesRead      = 0;
                var        iTotalBytesRead = 0;

                fs      = new FileStream(filename, FileMode.Create, FileAccess.Write);
                wRemote = WebRequest.Create(URL);
                var myWebResponse = await wRemote.GetResponseAsync().ConfigureAwait(true);

                FileDownloadSizeObtained?.Invoke(myWebResponse.ContentLength);
                var sChunks = myWebResponse.GetResponseStream();

                do
                {
                    iBytesRead = await sChunks.ReadAsync(bBuffer, 0, 256).ConfigureAwait(true);

                    await fs.WriteAsync(bBuffer, 0, iBytesRead).ConfigureAwait(true);

                    iTotalBytesRead += iBytesRead;

                    if (myWebResponse.ContentLength < iTotalBytesRead)
                    {
                        AmountDownloadedChanged?.Invoke(myWebResponse.ContentLength);
                    }
                    else
                    {
                        AmountDownloadedChanged?.Invoke(iTotalBytesRead);
                    }
                } while (iBytesRead != 0);

                sChunks.Close();
                fs.Close();

                FileDownloadComplete?.Invoke();

                return(true);
            }
            catch (Exception ex) {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }

                FileDownloadFailed?.Invoke(ex);
                return(false);
            }
        }
Beispiel #2
0
 /// <summary>
 /// Tải 1 tập tin
 /// </summary>
 /// <param name="URL">Liên kết của tập tin</param>
 /// <param name="filename">Nơi lưu</param>
 /// <returns></returns>
 public bool DownloadFile(string URL, string filename)
 {
     try {
         _currentFile = GetFileName(URL);
         using var wc = new WebClient();
         wc.DownloadFile(URL, filename);
         FileDownloadComplete?.Invoke();
         return(true);
     }
     catch (Exception ex) {
         FileDownloadFailed?.Invoke(ex);
         return(false);
     }
 }