實現(xiàn)原理:采用WebClient進(jìn)行批量下載任務(wù),簡單的模擬迅雷下載效果! 廢話不多說,先看掩飾效果: 具體實現(xiàn)步驟如下: 1.新建項目:WinBatchDownload 2.先建一個Windows窗體:FrmBatchDownload,加載事件FrmBatchDownload_Load 3.放置一個Button按鈕:btnStartDownLoad,單機(jī)事件btnStartDownLoad_Click 4.放置一個DataGridView:dgvDownLoad. 5.具體代碼如下: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; #region 命名空間 using System.Threading; using System.Runtime.InteropServices; using System.Net; using System.Collections; #endregion namespace WinBatchDownload { public partial class FrmBatchDownload : Form { #region 全局成員 //存放下載列表 List<SynFileInfo> m_SynFileInfoList; #endregion #region 構(gòu)造函數(shù) public FrmBatchDownload() { InitializeComponent(); m_SynFileInfoList = new List<SynFileInfo>(); } #endregion #region 窗體加載事件 private void FrmBatchDownload_Load(object sender, EventArgs e) { //初始化DataGridView相關(guān)屬性 InitDataGridView(dgvDownLoad); //添加DataGridView相關(guān)列信息 AddGridViewColumns(dgvDownLoad); //新建任務(wù) AddBatchDownload(); } #endregion #region 添加GridView列 /// <summary> /// 正在同步列表 /// </summary> void AddGridViewColumns(DataGridView dgv) { dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "DocID", HeaderText = "文件ID", Visible = false, Name = "DocID" }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { AutoSizeMode = DataGridViewAutoSizeColumnMode.None, DataPropertyName = "DocName", HeaderText = "文件名", Name = "DocName", Width = 300 }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "FileSize", HeaderText = "大小", Name = "FileSize", }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "SynSpeed", HeaderText = "速度", Name = "SynSpeed" }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "SynProgress", HeaderText = "進(jìn)度", Name = "SynProgress" }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "DownPath", HeaderText = "下載地址", Visible = false, Name = "DownPath" }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "SavePath", HeaderText = "保存地址", Visible = false, Name = "SavePath" }); dgv.Columns.Add(new DataGridViewTextBoxColumn() { DataPropertyName = "Async", HeaderText = "是否異步", Visible = false, Name = "Async" }); } #endregion #region 添加下載任務(wù)并顯示到列表中 void AddBatchDownload() { //清空行數(shù)據(jù) dgvDownLoad.Rows.Clear(); //添加列表(建立多個任務(wù)) List<ArrayList> arrayListList = new List<ArrayList>(); arrayListList.Add(new ArrayList(){ "0",//文件id "PPTV客戶端.exe",//文件名稱 "21.2 MB",//文件大小 "0 KB/S",//下載速度 "0%",//下載進(jìn)度 "http://download./pptvsetup_3.2.1.0076.exe",//遠(yuǎn)程服務(wù)器下載地址 "D:\\PPTV客戶端.exe",//本地保存地址 true//是否異步 }); arrayListList.Add(new ArrayList(){ "1", "PPS客戶端.exe", "14.3 MB", "0 KB/S", "0%", "http://download./ppstreamsetup.exe", "D:\\PPS客戶端.exe", true }); arrayListList.Add(new ArrayList(){ "2", "美圖看看客戶端.exe", "4.1 MB", "0 KB/S", "0%", "http://kankan.dl.meitu.com/V2/1029/KanKan_kk360Setup.exe", "D:\\美圖看看客戶端.exe", true }); foreach (ArrayList arrayList in arrayListList) { int rowIndex = dgvDownLoad.Rows.Add(arrayList.ToArray()); arrayList[2] = 0; arrayList.Add(dgvDownLoad.Rows[rowIndex]); //取出列表中的行信息保存列表集合(m_SynFileInfoList)中 m_SynFileInfoList.Add(new SynFileInfo(arrayList.ToArray())); } } #endregion #region 開始下載按鈕單機(jī)事件 private void btnStartDownLoad_Click(object sender, EventArgs e) { //判斷網(wǎng)絡(luò)連接是否正常 if (isConnected()) { //設(shè)置不可用 btnStartDownLoad.Enabled = false; //設(shè)置最大活動線程數(shù)以及可等待線程數(shù) ThreadPool.SetMaxThreads(3, 3); //判斷是否還存在任務(wù) if (m_SynFileInfoList.Count <= 0) AddBatchDownload(); foreach (SynFileInfo m_SynFileInfo in m_SynFileInfoList) { //啟動下載任務(wù) StartDownLoad(m_SynFileInfo); } } else { MessageBox.Show("網(wǎng)絡(luò)異常!"); } } #endregion #region 檢查網(wǎng)絡(luò)狀態(tài) //檢測網(wǎng)絡(luò)狀態(tài) [DllImport("wininet.dll")] extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue); /// <summary> /// 檢測網(wǎng)絡(luò)狀態(tài) /// </summary> bool isConnected() { int I = 0; bool state = InternetGetConnectedState(out I, 0); return state; } #endregion #region 使用WebClient下載文件 /// <summary> /// HTTP下載遠(yuǎn)程文件并保存本地的函數(shù) /// </summary> void StartDownLoad(object o) { SynFileInfo m_SynFileInfo = (SynFileInfo)o; m_SynFileInfo.LastTime = DateTime.Now; //再次new 避免WebClient不能I/O并發(fā) WebClient client = new WebClient(); if (m_SynFileInfo.Async) { //異步下載 client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(client_DownloadProgressChanged); client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadFileCompleted); client.DownloadFileAsync(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath, m_SynFileInfo); } else client.DownloadFile(new Uri(m_SynFileInfo.DownPath), m_SynFileInfo.SavePath); } /// <summary> /// 下載進(jìn)度條 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e) { SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState; m_SynFileInfo.SynProgress = e.ProgressPercentage + "%"; double secondCount = (DateTime.Now - m_SynFileInfo.LastTime).TotalSeconds; m_SynFileInfo.SynSpeed = FileOperate.GetAutoSizeString(Convert.ToDouble(e.BytesReceived / secondCount), 2) + "/s"; //更新DataGridView中相應(yīng)數(shù)據(jù)顯示下載進(jìn)度 m_SynFileInfo.RowObject.Cells["SynProgress"].Value = m_SynFileInfo.SynProgress; //更新DataGridView中相應(yīng)數(shù)據(jù)顯示下載速度(總進(jìn)度的平均速度) m_SynFileInfo.RowObject.Cells["SynSpeed"].Value = m_SynFileInfo.SynSpeed; } /// <summary> /// 下載完成調(diào)用 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void client_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e) { //到此則一個文件下載完畢 SynFileInfo m_SynFileInfo = (SynFileInfo)e.UserState; m_SynFileInfoList.Remove(m_SynFileInfo); if (m_SynFileInfoList.Count <= 0) { //此時所有文件下載完畢 btnStartDownLoad.Enabled = true; } } #endregion #region 需要下載文件實體類 class SynFileInfo { public string DocID { get; set; } public string DocName { get; set; } public long FileSize { get; set; } public string SynSpeed { get; set; } public string SynProgress { get; set; } public string DownPath { get; set; } public string SavePath { get; set; } public DataGridViewRow RowObject { get; set; } public bool Async { get; set; } public DateTime LastTime { get; set; } public SynFileInfo(object[] objectArr) { int i = 0; DocID = objectArr[i].ToString(); i++; DocName = objectArr[i].ToString(); i++; FileSize = Convert.ToInt64(objectArr[i]); i++; SynSpeed = objectArr[i].ToString(); i++; SynProgress = objectArr[i].ToString(); i++; DownPath = objectArr[i].ToString(); i++; SavePath = objectArr[i].ToString(); i++; Async = Convert.ToBoolean(objectArr[i]); i++; RowObject = (DataGridViewRow)objectArr[i]; } } #endregion #region 初始化GridView void InitDataGridView(DataGridView dgv) { dgv.AutoGenerateColumns = false;//是否自動創(chuàng)建列 dgv.AllowUserToAddRows = false;//是否允許添加行(默認(rèn):true) dgv.AllowUserToDeleteRows = false;//是否允許刪除行(默認(rèn):true) dgv.AllowUserToResizeColumns = false;//是否允許調(diào)整大小(默認(rèn):true) dgv.AllowUserToResizeRows = false;//是否允許調(diào)整行大小(默認(rèn):true) dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;//列寬模式(當(dāng)前填充)(默認(rèn):DataGridViewAutoSizeColumnsMode.None) dgv.BackgroundColor = System.Drawing.Color.White;//背景色(默認(rèn):ControlDark) dgv.BorderStyle = BorderStyle.Fixed3D;//邊框樣式(默認(rèn):BorderStyle.FixedSingle) dgv.CellBorderStyle = DataGridViewCellBorderStyle.SingleHorizontal;//單元格邊框樣式(默認(rèn):DataGridViewCellBorderStyle.Single) dgv.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.None;//列表頭樣式(默認(rèn):DataGridViewHeaderBorderStyle.Single) dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;//是否允許調(diào)整列大小(默認(rèn):DataGridViewColumnHeadersHeightSizeMode.EnableResizing) dgv.ColumnHeadersHeight = 30;//列表頭高度(默認(rèn):20) dgv.MultiSelect = false;//是否支持多選(默認(rèn):true) dgv.ReadOnly = true;//是否只讀(默認(rèn):false) dgv.RowHeadersVisible = false;//行頭是否顯示(默認(rèn):true) dgv.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//選擇模式(默認(rèn):DataGridViewSelectionMode.CellSelect) } #endregion #region 文件相關(guān)操作類分 /// <summary> /// 文件有關(guān)的操作類 /// </summary> public class FileOperate { #region 相應(yīng)單位轉(zhuǎn)換常量 private const double KBCount = 1024; private const double MBCount = KBCount * 1024; private const double GBCount = MBCount * 1024; private const double TBCount = GBCount * 1024; #endregion #region 獲取適應(yīng)大小 /// <summary> /// 得到適應(yīng)大小 /// </summary> /// <param name="size">字節(jié)大小</param> /// <param name="roundCount">保留小數(shù)(位)</param> /// <returns></returns> public static string GetAutoSizeString(double size, int roundCount) { if (KBCount > size) return Math.Round(size, roundCount) + "B"; else if (MBCount > size) return Math.Round(size / KBCount, roundCount) + "KB"; else if (GBCount > size) return Math.Round(size / MBCount, roundCount) + "MB"; else if (TBCount > size) return Math.Round(size / GBCount, roundCount) + "GB"; else return Math.Round(size / TBCount, roundCount) + "TB"; } #endregion } #endregion } }
到此批量下載功能實現(xiàn)完畢,上面寫的代碼比較靈活,需要的朋友可以根據(jù)自己的項目修改相關(guān)內(nèi)容。 最后附上源碼:WinBatchDownload.zip 作者:曾慶雷 出處:http://www.cnblogs.com/zengqinglei 本頁版權(quán)歸作者和博客園所有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明, 且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責(zé)任的權(quán)利 |
|