c# http下載 例子

来源:https://www.cnblogs.com/eliza209/archive/2019/09/07/11479031.html
-Advertisement-
Play Games

參考鏈接:https://www.cnblogs.com/taiyonghai/p/5604159.html 類: /******************************************************************************************* ...


參考鏈接:https://www.cnblogs.com/taiyonghai/p/5604159.html  

類:

/************************************************************************************************************************/

  1 using System;
  2 using System.Collections.Generic;
  3 using System.IO;
  4 using System.Linq;
  5 using System.Net;
  6 using System.Text;
  7 using System.Windows.Forms;
  8 using System.Threading.Tasks;
  9 using System.Threading;
 10 
 11 namespace httpTool
 12 {
 13     class HttpHelper
 14     {
 15         const int bytebuff = 1024;
 16         const int ReadWriteTimeOut = 2 * 1000;//超時等待時間
 17         const int TimeOutWait = 5 * 1000;//超時等待時間
 18         const int MaxTryTime = 12;
 19 
 20         private double totalSize, curReadSize, speed;
 21         private int proc, remainTime;
 22         private int totalTime = 0;
 23 
 24         bool downLoadWorking = false;
 25 
 26         string StrFileName = "";
 27         string StrUrl = "";
 28 
 29         string outMsg = "";
 30 
 31         public HttpHelper(string url, string savePath)
 32         {
 33             this.StrUrl = url;
 34             this.StrFileName = savePath;
 35         }
 36 
 37         /// <summary>
 38         /// 下載數據更新
 39         /// </summary>
 40         /// <param name="totalNum">下載文件總大小</param>
 41         /// <param name="num">已下載文件大小</param>
 42         /// <param name="proc">下載進度百分比</param>
 43         /// <param name="speed">下載速度</param>
 44         /// <param name="remainTime">剩餘下載時間</param>
 45         public delegate void delDownFileHandler(string totalNum, string num, int proc, string speed, string remainTime, string outMsg);
 46         public delDownFileHandler processShow;
 47         public delegate void delDownCompleted();
 48         public delDownCompleted processCompleted;
 49         public System.Windows.Forms.Timer timer;
 50 
 51         public void init()
 52         {
 53             timer.Interval = 100;
 54             timer.Tick -= TickEventHandler;
 55             timer.Tick += TickEventHandler;
 56             timer.Enabled = true;
 57             downLoadWorking = true;
 58         }
 59 
 60         /// <summary>
 61         /// 獲取文件大小
 62         /// </summary>
 63         /// <param name="size"></param>
 64         /// <returns></returns>
 65         private string GetSize(double size)
 66         {
 67             String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB" };
 68             double mod = 1024.0;
 69             int i = 0;
 70             while (size >= mod)
 71             {
 72                 size /= mod;
 73                 i++;
 74             }
 75             return Math.Round(size) + units[i];
 76         }
 77 
 78         /// <summary>
 79         /// 獲取時間
 80         /// </summary>
 81         /// <param name="second"></param>
 82         /// <returns></returns>
 83         private string GetTime(int second)
 84         {
 85             return new DateTime(1970, 01, 01, 00, 00, 00).AddSeconds(second).ToString("HH:mm:ss");
 86         }
 87 
 88         /// <summary>
 89         /// 下載文件(同步)  支持斷點續傳
 90         /// </summary>
 91         public void DowLoadFile()
 92         {
 93             totalSize = GetFileContentLength(StrUrl);
 94 
 95             //打開上次下載的文件或新建文件
 96             long lStartPos = 0;
 97             System.IO.FileStream fs;
 98             if (System.IO.File.Exists(StrFileName))
 99             {
100                 fs = System.IO.File.OpenWrite(StrFileName);
101                 lStartPos = fs.Length;
102                 fs.Seek(lStartPos, System.IO.SeekOrigin.Current);   //移動文件流中的當前指針
103             }
104             else
105             {
106                 fs = new System.IO.FileStream(StrFileName, System.IO.FileMode.Create);
107                 lStartPos = 0;
108             }
109 
110             curReadSize = lStartPos;
111 
112             if (curReadSize == totalSize)
113             {
114                 outMsg = "文件已下載!";
115                 processCompleted?.Invoke();
116                 timer.Enabled = false;
117                 return;
118             }
119 
120             //打開網路連接
121             try
122             {
123                 System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(StrUrl);
124                 if (lStartPos > 0)
125                     request.AddRange((int)lStartPos);    //設置Range值
126 
127                 //向伺服器請求,獲得伺服器回應數據流
128                 System.IO.Stream ns = request.GetResponse().GetResponseStream();
129                 byte[] nbytes = new byte[bytebuff];
130                 int nReadSize = 0;
131                 proc = 0;
132 
133                 do
134                 {
135 
136                     nReadSize = ns.Read(nbytes, 0, bytebuff);
137                     fs.Write(nbytes, 0, nReadSize);
138 
139                     //已下載大小
140                     curReadSize += nReadSize;
141                     //進度百分比
142                     proc = (int)((curReadSize / totalSize) * 100);
143                     //下載速度
144                     speed = (curReadSize / totalTime) * 10;
145                     //剩餘時間
146                     remainTime = (int)((totalSize / speed) - (totalTime / 10));
147 
148                     if (downLoadWorking == false)
149                         break;
150 
151                 } while (nReadSize > 0);
152 
153                 fs.Close();
154                 ns.Close();
155 
156                 if (curReadSize == totalSize)
157                 {
158                     outMsg = "下載完成!";
159                     processCompleted?.Invoke();
160                     downLoadWorking = false;
161                 }
162             }
163             catch (Exception ex)
164             {
165                 fs.Close();
166                 outMsg = string.Format("下載失敗:{0}", ex.ToString());
167             }
168         }
169 
170         public void DownLoadPause()
171         {
172             outMsg = "下載已暫停";
173             downLoadWorking = false;
174         }
175 
176         public void DownLoadContinue()
177         {
178             outMsg = "正在下載";
179             downLoadWorking = true;
180             DownLoadStart();
181         }
182 
183         public void DownLoadStart()
184         {
185             Task.Run(() =>
186             {
187                 DowLoadFile();
188             });
189         }
190 
191 
192         /// <summary>
193         /// 定時器方法
194         /// </summary>
195         /// <param name="sender"></param>
196         /// <param name="e"></param>
197         private void TickEventHandler(object sender, EventArgs e)
198         {
199             processShow?.Invoke(GetSize(totalSize),
200                                 GetSize(curReadSize),
201                                 proc,
202                                 string.Format("{0}/s", GetSize(speed)),
203                                 GetTime(remainTime),
204                                 outMsg
205                                 );
206             if (downLoadWorking == true)
207             {
208                 totalTime++;
209             }
210         }
211 
212         /// <summary>
213         /// 獲取下載文件長度
214         /// </summary>
215         /// <param name="url"></param>
216         /// <returns></returns>
217         public long GetFileContentLength(string url)
218         {
219             HttpWebRequest request = null;
220             try
221             {
222                 request = (HttpWebRequest)HttpWebRequest.Create(url);
223                 //request.Timeout = TimeOutWait;
224                 //request.ReadWriteTimeout = ReadWriteTimeOut;
225                 //向伺服器請求,獲得伺服器回應數據流
226                 WebResponse respone = request.GetResponse();
227                 request.Abort();
228                 return respone.ContentLength;
229             }
230             catch (Exception e)
231             {
232                 if (request != null)
233                     request.Abort();
234                 return 0;
235             }
236         }
237     }
238 }

 

頁面調用

/***************************************************************************************************************/

 1 using System;
 2 using System.Collections.Generic;
 3 using System.ComponentModel;
 4 using System.Data;
 5 using System.Drawing;
 6 using System.Linq;
 7 using System.Text;
 8 using System.Threading.Tasks;
 9 using System.Windows.Forms;
10 using httpTool;
11 using System.Threading;
12 
13 namespace DownLoadDemo1
14 {
15     public partial class Form1 : Form
16     {
17         static string url = "http://speedtest.dallas.linode.com/100MB-dallas.bin"; //下載地址
18 
19         static string temp = System.Environment.GetEnvironmentVariable("TEMP");
20         static string loadFilefolder = new System.IO.DirectoryInfo(temp).FullName + @"\" + "100MB-dallas.bin";
21 
22         Thread td;
23         HttpHelper httpManager = new HttpHelper(url, loadFilefolder);
24 
25         public Form1()
26         {
27             InitializeComponent();
28         }
29 
30         private void Form1_Load(object sender, EventArgs e)
31         {
32             httpManager.timer = new System.Windows.Forms.Timer();
33             httpManager.processShow += processSho;
34             httpManager.processCompleted += processComplete;
35             httpManager.init();
36 
37         }
38 
39         public void processSho(string totalNum, string num, int proc, string speed, string remainTime, string msg)
40         {
41             this.label1.Text = string.Format("文件大小:{0}", totalNum);
42             this.label2.Text = string.Format("已下載:{0}", num);
43             this.label3.Text = string.Format("進度:{0}%", proc);
44             this.label4.Text = msg;
45             this.label5.Text = string.Format("速度:{0}",speed);
46             this.label6.Text = string.Format("剩餘時間:{0}",remainTime);
47         }
48 
49         private void processComplete()
50         {
51             MessageBox.Show("文件下載完成!", "提示");
52         }
53 
54         private void button1_Click(object sender, EventArgs e)
55         {
56             httpManager.DownLoadStart();
57 
58         }
59 
60         private void button2_Click(object sender, EventArgs e)
61         {
62             httpManager.DownLoadPause();
63         }
64 
65         private void button3_Click(object sender, EventArgs e)
66         {
67             httpManager.DownLoadContinue();
68         }
69     }
70 }

效果

/*********************************************************************************/

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • java模擬多ip請求 package url_demo; import java.util.Random; public class DemoUtl { public static int index = 0; public static void main(String[] args) thro ...
  • 場景 CSDN: https://blog.csdn.net/badao_liumang_qizhi 博客園: https://www.cnblogs.com/badaoliumangqizhi/ 嗶哩嗶哩視頻教程: https://space.bilibili.com/164396311 實現 關 ...
  • 一、此處主要介紹在springboot工程下如何使用 logback + slf4j 進行日誌記錄。 logback主要包含三個組成部分:Loggers(日誌記錄器)、Appenders(輸出目的在)、Layouts(日誌輸出格式) slf4j :如jdbc一樣,定義了一套介面,是一個日誌門面,可實 ...
  • 引言 我們知道開發最好用Mac/Linux,效率很高,但是對於很多還是Windows用戶的我們來說,編寫代碼再到linux上運行也是很常有的事情,但對於我們寫一些小demo使用上面的流程難免有點興師動眾,傷元氣的事情程式員只會掉發更快,所以再Windows搭建gcc開發環境還是很有必要的,MinGW ...
  • websocket消息服務 目的:搭建websocket服務,用瀏覽器與服務進行消息交互(寫的第一個Go程式) 代碼目錄結構: 前端html頁面: 1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <script> 6 wi ...
  • 題目描述: 給定兩個整數 a, b (a, b 均不超過 int 類型的表示範圍),求出 a + b 的和。輸入描述: 多組輸入,每組輸入為一行,裡面有 2 個數 a, b。輸出描述: 對於每一組輸入,輸出一個值為該組 a + b 的和。樣例輸入: 1 2 2 3樣例輸出: 3 5 ...
  • Linux系統大多數都支持OpenSSH,生成公鑰、私鑰的最好用ssh-keygen命令,如果用putty自帶的PUTTYGEN.EXE生成會不相容OpenSSH,從而會導致登錄時出現server refused our key錯誤。 ...
  • 繼承 什麼是繼承?就是一個派生類(derived class)繼承基類(base class)的欄位和方法。一個類可以被多個類繼承;在python中,一個類可以繼承多個類。 父類可以稱為基類和超類,而子類可以稱為派生類 在繼承中可分為單繼承和多繼承兩種 下麵是繼承的用法,語法為'class 子類的名 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...