Exemplo n.º 1
0
        /// <summary>
        /// 执行文件下载
        /// </summary>
        /// <param name="url"></param>
        /// <param name="savePath"></param>
        /// <param name="downloadFileHandler"></param>
        public void downloadFile(string url, string savePath, DownloadFileHandler downloadFileHandler)
        {
            this.downloadFileHandler = downloadFileHandler;
            this.url      = url;
            this.savePath = savePath;

            try
            {
                // 创建目录
                System.IO.Directory.CreateDirectory(Path.GetDirectoryName(savePath));

                if (File.Exists(savePath))
                {
                    File.Delete(savePath);
                }

                wc = new WebClient();
                wc.DownloadProgressChanged += WebClientDownloadProgressChanged;
                wc.DownloadDataCompleted   += WebClientDownloadCompleted;
                wc.DownloadDataAsync(new Uri(url));

                // Sync
                //byte[] bf = wc.DownloadData(new System.Uri(url));
                //ByteArrayToFile(savePath, bf);

                // DownloadFileAsync存在文件不释放问题
                // wc.DownloadFileAsync(new System.Uri(url), savePath);
            }
            catch (Exception ex)
            {
                downloadCro.IsSuccess = false;
                downloadCro.Message   = ex.Message;
                downloadFileHandler?.Invoke(downloadCro);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// 下载完成回调函数
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void WebClientDownloadCompleted(object sender, DownloadDataCompletedEventArgs e)
        {
            try
            {
                byte[] bf = e.Result;
                ByteArrayToFile(savePath, bf);

                downloadCro.IsSuccess = true;
                downloadCro.Message   = "Download finished!";
            }
            catch (Exception ex)
            {
                downloadCro.IsSuccess = false;
                downloadCro.Message   = "Download fail! " + ex.Message;
            }

            finally
            {
                downloadCro.LocalPath = savePath;

                downloadFileHandler?.Invoke(downloadCro);
            }
        }