網(wǎng)站運營seo文章大全提供全面的站長運營經(jīng)驗及seo技術!一.概述:
本文通過一個實例向大家介紹用visual c#進行internet通訊編程的一些基本知識。我們知道.net類包含了請求/響應層、應用協(xié)議層、傳輸層等層次。在本程序中,我們運用了位于請求/響應層的webrequest類以及webclient類等來實現(xiàn)高抽象程度的internet通訊服務。本程序的功能是完成網(wǎng)絡文件的下載。
二.實現(xiàn)原理:
程序實現(xiàn)的原理比較簡單,主要用到了webclient類和filestream類。其中webclient類處于system.net名字空間中,該類的主要功能是提供向uri標識的資源發(fā)送數(shù)據(jù)和從uri標識的資源接收數(shù)據(jù)的公共方法。我們利用其中的downloadfile()方法將網(wǎng)絡文件下載到本地。然后用filestream類的實例對象以數(shù)據(jù)流的方式將文件數(shù)據(jù)寫入本地文件。這樣就完成了網(wǎng)絡文件的下載。
三.實現(xiàn)步驟:
首先,打開visual studio.net,新建一個visual c# windows應用程序的工程,不妨命名為"mygetcar"。
接著,布置主界面。我們先往主窗體上添加如下控件:兩個標簽控件、兩個文本框控件、一個按鈕控件以及一個狀態(tài)欄控件。最終的主窗體如下圖所示:
完成主窗體的設計,我們接著完成代碼的編寫。
在理解了基本原理的基礎上去完成代碼的編寫是相當容易。程序中我們主要用到的是webclient類,不過在我們調(diào)用webclient類的實例對象前,我們需要用webrequest類的對象發(fā)出對統(tǒng)一資源標識符(uri)的請求。
try
{
webrequest myre=webrequest.create(urladdress);
}
catch(webexception exp)
{
messagebox.show(exp.message,"error");
}
這是一個try-catch語句,try塊完成向uri的請求,catch塊則捕捉可能的異常并顯示異常信息。其中的urladdress為被請求的網(wǎng)絡主機名。
在請求成功后,我們就可以運用webclient類的實例對象中的downloadfile()方法實現(xiàn)文件的下載了。其函數(shù)原型如下:
public void downloadfile( string address, string filename);
其中,參數(shù)address為從中下載數(shù)據(jù)的 uri,filename為要接收數(shù)據(jù)的本地文件的名稱。
之后我們用openread()方法來打開一個可讀的流,該流完成從具有指定uri的資源下載數(shù)據(jù)的功能。其函數(shù)原型如下:
ublic stream openread(string address);
其中,參數(shù)address同上。
最后就是新建一個streamreader對象從中讀取文件的數(shù)據(jù),并運用一個while循環(huán)體不斷讀取數(shù)據(jù),只到讀完所有的數(shù)據(jù)。
還有在使用以上方法時,你將可能需要處理以下幾種異常:
webexception:下載數(shù)據(jù)時發(fā)生錯誤。
uriformatexception:通過組合 baseaddress、address 和 querystring 所構成的 uri 無效。
這部分的代碼如下:(client為webclient對象,在本類的開頭處聲明即可)
statusbar.text = "開始下載文件...";
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;
}
完成了文件數(shù)據(jù)的讀取工作后,我們運用filestream類的實例對象將這些數(shù)據(jù)寫入本地文件中:
filestream fstr = new filestream(path,filemode.openorcreate,fileaccess.write);
fstr.write(mbyte,0,startmbyte);
這樣,程序主體部分的代碼已經(jīng)完成了,不過要完成全部程序還需要一些工作。由于在程序接收網(wǎng)絡文件數(shù)據(jù)的時候運用到了while循環(huán)體,這樣會很占程序資源,表現(xiàn)的形式就是主窗體不能自由移動。為了解決這個問題,我們在程序中用到了多線程機制。我們在響應按鈕的事件中新建一個線程,該線程就是用來實現(xiàn)網(wǎng)絡文件下載功能的。如此,文件下載的線程和程序主線程并存,共享進程資源,使得程序順暢運行。這樣,我們在按鈕控件的消息響應函數(shù)里添加如下代碼:
thread th = new thread(new threadstart(startdownload));
th.start();
該線程的實現(xiàn)函數(shù)就是startdownload(),而上面介紹的那些代碼就是這個函數(shù)的主體部分。
最后,因為程序中運用到了webrequest、webclient、filestream、thread等類,所以最重要的就是在程序的開始處添加如下名字空間:
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 的摘要說明。
///
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();
///
/// 必需的設計器變量。
///
private system.componentmodel.container components = null;
public form1()
{
//
// windows 窗體設計器支持所必需的
//
initializecomponent();
//
// todo: 在 initializecomponent 調(diào)用后添加任何構造函數(shù)代碼
//
}
///
/// 清理所有正在使用的資源。
///
protected override void dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.dispose();
}
}
base.dispose( disposing );
}
#region windows form designer generated code
///
/// 設計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(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 = "開始下載";
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;
this.name = "form1";
this.text = "文件下載器";
this.resumelayout(false);
}
#endregion
///
/// 應用程序的主入口點。
///
[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 = "開始下載文件...";
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();
}
}
}
程序完畢,運行程序圖示如下:
(開始下載文件時)
(文件下載完畢時)
四.總結:
以上我通過一個實例向大家展示了如何用visual c#實現(xiàn)網(wǎng)絡文件的下載,我們不難發(fā)現(xiàn)用visual c#進行internet通訊編程是非常方便的。在上面的程序中,我們僅僅用到了webclient類的一些方法,而webclient類不光提供了網(wǎng)絡文件下載的方法,還提供了文件上傳的方法,有興趣的讀者不妨一試――用之實現(xiàn)一個文件上傳器。同時這個程序只是一個非常簡單的例子,程序下載完一個網(wǎng)頁后,它所獲得的僅僅是主頁面的內(nèi)容,并不能獲得其中的圖片、css等文件,所以要做出一個比較好的文件下載器還需讀者進一步改進之。