C#实现文件下载代码
提供個(gè)C#實(shí)現(xiàn)文件下載代碼
一.概述:
本文通過(guò)一個(gè)實(shí)例向大家介紹用Visual C#進(jìn)行Internet通訊編程的一些基本知識(shí)。我們知道.Net類包含了請(qǐng)求/響應(yīng)層、應(yīng)用協(xié)議層、傳輸層等層次。在本程序中,我們運(yùn)用了位于請(qǐng)求/響應(yīng)層的WebRequest類以及WebClient類等來(lái)實(shí)現(xiàn)高抽象程度的Internet通訊服務(wù)。本程序的功能是完成網(wǎng)絡(luò)文件的下載。
二.實(shí)現(xiàn)原理:
程序?qū)崿F(xiàn)的原理比較簡(jiǎn)單,主要用到了WebClient類和FileStream類。其中WebClient類處于System.Net名字空間中,該類的主要功能是提供向URI標(biāo)識(shí)的資源發(fā)送數(shù)據(jù)和從URI標(biāo)識(shí)的資源接收數(shù)據(jù)的公共方法。我們利用其中的DownloadFile()方法將網(wǎng)絡(luò)文件下載到本地。然后用FileStream類的實(shí)例對(duì)象以數(shù)據(jù)流的方式將文件數(shù)據(jù)寫(xiě)入本地文件。這樣就完成了網(wǎng)絡(luò)文件的下載。
三.實(shí)現(xiàn)步驟:
首先,打開(kāi)Visual Studio.Net,新建一個(gè)Visual C# Windows應(yīng)用程序的工程,不妨命名為\"MyGetCar\"。
接著,布置主界面。我們先往主窗體上添加如下控件:兩個(gè)標(biāo)簽控件、兩個(gè)文本框控件、一個(gè)按鈕控件以及一個(gè)狀態(tài)欄控件。
完成主窗體的設(shè)計(jì),我們接著完成代碼的編寫(xiě)。
在理解了基本原理的基礎(chǔ)上去完成代碼的編寫(xiě)是相當(dāng)容易。程序中我們主要用到的是WebClient類,不過(guò)在我們調(diào)用WebClient類的實(shí)例對(duì)象前,我們需要用WebRequest類的對(duì)象發(fā)出對(duì)統(tǒng)一資源標(biāo)識(shí)符(URI)的請(qǐng)求。
try
{
WebRequest myre=WebRequest.Create(URLAddress);
}
catch(WebException exp)
{
MessageBox.Show(exp.Message,\"Error\");
}
這是一個(gè)try-catch語(yǔ)句,try塊完成向URI的請(qǐng)求,catch塊則捕捉可能的異常并顯示異常信息。其中的URLAddress為被請(qǐng)求的網(wǎng)絡(luò)主機(jī)名。
在請(qǐng)求成功后,我們就可以運(yùn)用WebClient類的實(shí)例對(duì)象中的DownloadFile()方法實(shí)現(xiàn)文件的下載了。其函數(shù)原型如下:
public void DownloadFile( string address, string fileName);
其中,參數(shù)address為從中下載數(shù)據(jù)的 URI,fileName為要接收數(shù)據(jù)的本地文件的名稱。
之后我們用OpenRead()方法來(lái)打開(kāi)一個(gè)可讀的流,該流完成從具有指定URI的資源下載數(shù)據(jù)的功能。其函數(shù)原型如下:
public Stream OpenRead(string address);
其中,參數(shù)address同上。
最后就是新建一個(gè)StreamReader對(duì)象從中讀取文件的數(shù)據(jù),并運(yùn)用一個(gè)while循環(huán)體不斷讀取數(shù)據(jù),只到讀完所有的數(shù)據(jù)。
還有在使用以上方法時(shí),你將可能需要處理以下幾種異常:
WebException:下載數(shù)據(jù)時(shí)發(fā)生錯(cuò)誤。
UriFormatException:通過(guò)組合 BaseAddress、address 和 QueryString 所構(gòu)成的 URI 無(wú)效。
這部分的代碼如下:(client為WebClient對(duì)象,在本類的開(kāi)頭處聲明即可)
statusBar.Text = \"開(kāi)始下載文件...\";
client.DownloadFile(URLAddress,fileName);
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[100000];
int allmybyte = (int)mbyte.Length;[Page]
int startmbyte = 0;
statusBar.Text = \"正在接收數(shù)據(jù)...\";
while(allmybyte>0)
{
int m = str.Read(mbyte,startmbyte,allmybyte);
if(m==0)
break;
startmbyte+=m;
allmybyte-=m;
}
完成了文件數(shù)據(jù)的讀取工作后,我們運(yùn)用FileStream類的實(shí)例對(duì)象將這些數(shù)據(jù)寫(xiě)入本地文件中:
FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write);
fstr.Write(mbyte,0,startmbyte);
這樣,程序主體部分的代碼已經(jīng)完成了,不過(guò)要完成全部程序還需要一些工作。由于在程序接收網(wǎng)絡(luò)文件數(shù)據(jù)的時(shí)候運(yùn)用到了while循環(huán)體,這樣會(huì)很占程序資源,表現(xiàn)的形式就是主窗體不能自由移動(dòng)。為了解決這個(gè)問(wèn)題,我們?cè)诔绦蛑杏玫搅硕嗑€程機(jī)制。我們?cè)陧憫?yīng)按鈕的事件中新建一個(gè)線程,該線程就是用來(lái)實(shí)現(xiàn)網(wǎng)絡(luò)文件下載功能的。如此,文件下載的線程和程序主線程并存,共享進(jìn)程資源,使得程序順暢運(yùn)行。這樣,我們?cè)诎粹o控件的消息響應(yīng)函數(shù)里添加如下代碼:
Thread th = new Thread(new ThreadStart(StartDownload));
th.Start();
該線程的實(shí)現(xiàn)函數(shù)就是StartDownload(),而上面介紹的那些代碼就是這個(gè)函數(shù)的主體部分。
最后,因?yàn)槌绦蛑羞\(yùn)用到了WebRequest、WebClient、FileStream、Thread等類,所以最重要的就是在程序的開(kāi)始處添加如下名字空間:
using System.Net;
using System.IO;
using System.Threading;
下面就是程序的源代碼:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Net;
using System.IO;
using System.Threading;
namespace MyGetCar
{
///
/// Form1 的摘要說(shuō)明。
///
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox srcAddress;
private System.Windows.Forms.TextBox tarAddress;
private System.Windows.Forms.StatusBar statusBar;
private System.Windows.Forms.Button Start;
private WebClient client = new WebClient();
///
/// 必需的設(shè)計(jì)器變量。
///
private System.ComponentModel.Container components = null;
public Form1()
{
//
// Windows 窗體設(shè)計(jì)器支持所必需的
InitializeComponent();
//
// TODO: 在 InitializeComponent 調(diào)用后添加任何構(gòu)造函數(shù)代碼
//
}
///
/// 清理所有正在使用的資源。
///
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code[Page]
/// 設(shè)計(jì)器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(nèi)容。
///
private void InitializeComponent()
{
this.label1 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.srcAddress = new System.Windows.Forms.TextBox();
this.tarAddress = new System.Windows.Forms.TextBox();
this.statusBar = new System.Windows.Forms.StatusBar();
this.Start = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// label1
//
this.label1.Location = new System.Drawing.Point(8, 32);
this.label1.Name = \"label1\";
this.label1.Size = new System.Drawing.Size(72, 23);
this.label1.TabIndex = 0;
this.label1.Text = \"文件地址:\";
this.label1.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 72);
this.label2.Name = \"label2\";
this.label2.Size = new System.Drawing.Size(72, 23);
this.label2.TabIndex = 1;
this.label2.Text = \"另存到:\";
this.label2.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// srcAddress
//
this.srcAddress.Location = new System.Drawing.Point(80, 32);
this.srcAddress.Name = \"srcAddress\";
this.srcAddress.Size = new System.Drawing.Size(216, 21);
this.srcAddress.TabIndex = 2;
this.srcAddress.Text = \"\";
//
// tarAddress
//
this.tarAddress.Location = new System.Drawing.Point(80, 72);
this.tarAddress.Name = \"tarAddress\";
this.tarAddress.Size = new System.Drawing.Size(216, 21);
this.tarAddress.TabIndex = 3;
this.tarAddress.Text = \"\";
//
// statusBar
//
this.statusBar.Location = new System.Drawing.Point(0, 151);
this.statusBar.Name = \"statusBar\";
this.statusBar.Size = new System.Drawing.Size(312, 22);
this.statusBar.TabIndex = 4;
//
// Start
//
this.Start.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.Start.Location = new System.Drawing.Point(216, 112);
this.Start.Name = \"Start\";
this.Start.Size = new System.Drawing.Size(75, 24);
this.Start.TabIndex = 5;
this.Start.Text = \"開(kāi)始下載\";
this.Start.Click += new System.EventHandler(this.Start_Click);
//
// Form1
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 14);
this.ClientSize = new System.Drawing.Size(312, 173);
this.Controls.AddRange(new System.Windows.Forms.Control[] {
this.Start,
this.statusBar,
this.tarAddress,
this.srcAddress,
this.label2,
this.label1});
this.MaximizeBox = false;[Page]
this.Name = \"Form1\";
this.Text = \"文件下載器\";
this.ResumeLayout(false);
}
#endregion
///
/// 應(yīng)用程序的主入口點(diǎn)。
///
[STAThread]
static void Main()
{
Application.Run(new Form1());
}
private void StartDownload()
{
Start.Enabled = false;
string URL = srcAddress.Text;
int n = URL.LastIndexOf(\"/\");
string URLAddress = URL.Substring(0,n);
string fileName = URL.Substring(n+1,URL.Length-n-1);
string Dir = tarAddress.Text;
string Path = Dir+\"\\\\\"+fileName;
try
{
WebRequest myre=WebRequest.Create(URLAddress);
}
catch(WebException exp)
{
MessageBox.Show(exp.Message,\"Error\");
}
try
{
statusBar.Text = \"開(kāi)始下載文件...\";
client.DownloadFile(URLAddress,fileName);
Stream str = client.OpenRead(URLAddress);
StreamReader reader = new StreamReader(str);
byte[] mbyte = new byte[100000];
int allmybyte = (int)mbyte.Length;
int startmbyte = 0;
statusBar.Text = \"正在接收數(shù)據(jù)...\";
while(allmybyte>0)
{
int m = str.Read(mbyte,startmbyte,allmybyte);
if(m==0)
break;
startmbyte+=m;
allmybyte-=m;
}
FileStream fstr = new FileStream(Path,FileMode.OpenOrCreate,FileAccess.Write);
fstr.Write(mbyte,0,startmbyte);
str.Close();
fstr.Close();
statusBar.Text = \"下載完畢!\";
}
catch(WebException exp)
{
MessageBox.Show(exp.Message,\"Error\");
statusBar.Text = \"\";
}
Start.Enabled = true;
}
private void Start_Click(object sender, System.EventArgs e)
{
Thread th = new Thread(new ThreadStart(StartDownload));
th.Start();
}
}
}
四.總結(jié):
以上我通過(guò)一個(gè)實(shí)例向大家展示了如何用Visual C#實(shí)現(xiàn)網(wǎng)絡(luò)文件的下載,我們不難發(fā)現(xiàn)用Visual C#進(jìn)行Internet通訊編程是非常方便的。在上面的程序中,我們僅僅用到了WebClient類的一些方法,而WebClient類不光提供了網(wǎng)絡(luò)文件下載的方法,還提供了文件上傳的方法,有興趣的讀者不妨一試――用之實(shí)現(xiàn)一個(gè)文件上傳器。同時(shí)這個(gè)程序只是一個(gè)非常簡(jiǎn)單的例子,程序下載完一個(gè)網(wǎng)頁(yè)后,它所獲得的僅僅是主頁(yè)面的內(nèi)容,并不能獲得其中的圖片、CSS等文件,所以要做出一個(gè)比較好的文件下載器還需讀者進(jìn)一步改進(jìn)之。
?
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的C#实现文件下载代码的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: ProcExp的利用
- 下一篇: python如何调用hslcommuni