域名频道-专业提供域名注册,网站空间,电子邮箱,VPS主机等服务
首页 域名注册 虚拟主机 香港主机 美国主机 VPS主机 网站建设 ShopEX网店 软件开发 客户中心 购物车
域名服务,域名注册 常见问题
文章搜索


本类TOP10
·松江网页设计_松江网页制...
·上海轨道交通图-上海地图
·松江公交线路图-松江地图
·marquee连续滚动
·今天几度?-天气预报-全...
·松江新城地图-松江地图
·松江城区地图-松江地图
·HAO123邮箱登陆代码
·shopex免费模板,下...
·松江DNS服务器地址,松...
当前位置:域名频道首页 > 常见问题 > 网页制作
用C#实现文件下载器(2)

这样,程序主体部分的代码已经完成了,不过要完 成全部程序还需要一些工作。由于在程序接收网络文件数据的时候运 用到了while循环体,这样会很占程序资源,表现的形式就是主 窗体不能自由移动。为了解决这个问题,我们在程序中用到了多线程 机制。我们在响应按钮的事件中新建一个线程,该线程就是用来实现 网络文件下载功能的。如此,文件下载的线程和程序主线程并存,共 享进程资源,使得程序顺畅运行。这样,我们在按钮控件的消息响应 函数里添加如下代码:

 

Thread th = new Thread(new Thr eadStart(StartDownload));

t h.Start();

 


该线 程的实现函数就是StartDownload(),而上面介绍的 那些代码就是这个函数的主体部分。
最后,因为程序中运用 到了WebRequest、WebClient、FileStr eam、Thread等类,所以最重要的就是在程序的开始处添加 如下名字空间:

 

usi ng System.Net;

using System .IO;

using System.Threading ;

 


下面就是程序的源代码:

 

using Syst em;

using System.Drawing;
using System.Collections;

using System.ComponentModel;
< br>using System.Windows.Forms;

using System.Data;

usin g System.Net;

using System. IO;

using System.Threading;


namespace MyGetCar
{
/// &
lt;
summary&
gt;

/// Form1 的摘要说明。
/ // &
lt;
/summary&
gt;

public class Form1 : System. Windows.Forms.Form
{
private System.Windows.Forms.L abel label1;

private Syst em.Windows.Forms.Label label2;

private System.Windows.F orms.TextBox srcAddress;

private System.Windows.Forms.T extBox tarAddress;

privat e System.Windows.Forms.StatusB ar statusBar;

private Sys tem.Windows.Forms.Button Start ;


private WebClient c lient = new WebClient();

/// &
lt;
summary&
gt ;

/// 必需的设计器变量。
/// &
lt;
/summary&
gt;

private System.ComponentModel. Container components = null;

public Form1()
{< br> //
// Windows 窗体设计 器支持所必需的
//
Initial izeComponent();


// // TODO: 在 InitializeComp onent 调用后添加任何构造函数代码
// }

/// &
lt;
sum mary&
gt;

/// 清理所有正在使用 的资源。
/// &
lt;
/summary &
gt;

protected overri de void Dispose( bool disposin g )
{
if( disposing )
{
if (componen ts != null)
{
components.Dispose();

}
}
base.Dispose( d isposing );

}

#r egion Windows Form Designer ge nerated code
/// &
lt;
summary&
gt;

/// 设计器支持 所需的方法 - 不要使用代码编辑器修改
/// 此 方法的内容。
/// &
lt;
/summa ry&
gt;

private void I nitializeComponent()
{
this.label1 = new System.W indows.Forms.Label();

th is.label2 = new System.Windows .Forms.Label();

this.src Address = new System.Windows.F orms.TextBox();

this.tar Address = new System.Windows.F orms.TextBox();

this.sta tusBar = new System.Windows.Fo rms.StatusBar();

this.St art = new System.Windows.Forms .Button();

this.SuspendL ayout();

//
// la bel1
//
this.labe l1.Location = new System.Drawi ng.Point(8, 32);

this.la bel1.Name = &
quot;
label1&a mp;
quot;
;

this.label1.Si ze = new System.Drawing.Size(7 2, 23);

this.label1.TabI ndex = 0;

this.label1.Te xt = &
quot;
文件地址:&
quot;
;

this.label1.TextAlign =
System.Drawing.ContentAl ignment.MiddleRight;

//
// label2
//
this.label2.Location = new System.Drawing.Point(8, 72);
this.label2.Name = &
q uot;
label2&
quot;
;

th is.label2.Size = new System.Dr awing.Size(72, 23);

this .label2.TabIndex = 1;

th is.label2.Text = &
quot;
另存到 :&
quot;
;

this.label2 .TextAlign =
System.Drawin g.ContentAlignment.MiddleRight ;

//
// srcAddres s
//
this.srcAddr ess.Location = new System.Draw ing.Point(80, 32);

this. srcAddress.Name = &
quot;
sr cAddress&
quot;
;

this .srcAddress.Size = new System. Drawing.Size(216, 21);

t his.srcAddress.TabIndex = 2;
this.srcAddress.Text = &a mp;
quot;
&
quot;
;

// < br> // tarAddress
// < br> this.tarAddress.Location = new System.Drawing.Point(80 , 72);

this.tarAddress.N ame = &
quot;
tarAddress& ;
quot;
;

this.tarAddress. Size = new System.Drawing.Size (216, 21);

this.tarAddre ss.TabIndex = 3;

this.ta rAddress.Text = &
quot;
& ;
quot;
;

//
// sta tusBar
//
this.st atusBar.Location = new System. Drawing.Point(0, 151);

t his.statusBar.Name = &
quot ;
statusBar&
quot;
;

th is.statusBar.Size = new System .Drawing.Size(312, 22);

this.statusBar.TabIndex = 4;
//
// Start
//
this.Start.FlatStyle = System.Windows.Forms.FlatSt yle.Flat;

this.Start.Loc ation = new System.Drawing.Poi nt(216, 112);

this.Start .Name = &
quot;
Start&
qu ot;
;

this.Start.Size = n ew System.Drawing.Size(75, 24) ;

this.Start.TabIndex = 5;

this.Start.Text = &am p;
quot;
开始下载&
quot;
;

t his.Start.Click += new
Sys tem.EventHandler(this.Start_Cl ick);

//
// Form1
//
this.AutoScal eBaseSize = new System.Drawing .Size(6, 14);

this.Clien tSize = new System.Drawing.Siz e(312, 173);

this.Contro ls.AddRange(new System.Windows .Forms.Control[] {
this.St art,
this.statusBar,
t his.tarAddress,
this.srcAd dress,
this.label2,
th is.label1});

this.MaximizeB ox = false;

this.Name = &am p;
quot;
Form1&
quot;
;

thi s.Text = &
quot;
文件下载器&
q uot;
;

this.ResumeLayout(fal se);

}
#endregion
/// &
lt;
summary&
gt;

// / 应用程序的主入口点。
/// &
lt;
/s ummary&
gt;

[STAThread]< br>static void Main()
{ Application.Run(new Form1() );

}
private void Sta rtDownload()
{
Star t.Enabled = false;

strin g URL = srcAddress.Text;

int n = URL.LastIndexOf('/');

string URLAddress = URL .Substring(0,n);

string fileName = URL.Substring(n+1,U RL.Length-n-1);

string D ir = tarAddress.Text;

st ring Path = Dir+'\\'+fileName;


try
{
WebRequest myre=WebRequest. Create(URLAddress);

}
catch(WebException exp)
{
MessageBox.Show(e xp.Message,&
quot;
Error& ;
quot;
);

}

try
{
statusBar.Text = &
quot;
开始下载文件...&
quo t;
;

client.DownloadFile (URLAddress,fileName);

Stream str = client.OpenRead(U RLAddress);

StreamReade r reader = new StreamReader(s tr);

byte[] mbyte = new byte[100000];

int allm ybyte = (int)mbyte.Length;

int startmbyte = 0;

statusBar.Text = &
quot;
正在 接收数据...&
quot;
;

whil e(allmybyte&
gt;
0)
{
int m =
str.Read( mbyte,startmbyte,allmybyte);
if(m==0)
break ;


startmbyte+= m;

allmybyte-=m;

}

FileStream fstr = new
FileStream(Path,Fil eMode.OpenOrCreate,FileAccess. Write);

fstr.Write(mbyt e,0,startmbyte);

str.Cl ose();

fstr.Close();


statusBar.Text = &
quot;
下载完毕!&
quot;
;
}
catch(WebExceptio n exp)
{
MessageB ox.Show(exp.Message,&
quot;
Error&
quot;
);

statu sBar.Text = &
quot;
&
quo t;
;

}

Start .Enabled = true;

}

private void Start_Click(ob ject sender, System.EventArgs e)
{
Thread th = ne w Thread(new ThreadStart(Start Download));

th.Start();
< br> }
}
}

 

程序完毕,运行程序图示如下:

(开始下载文件时)

(文件下载完毕时) < br>
总结

 

以上我 通过一个实例向大家展示了如何用C#实现网络文件的下载,我们不 难发现用C#进行Internet通讯编程是非常方便的。在上面 的程序中,我们仅仅用到了WebClient类的一些方法,而W ebClient类不光提供了网络文件下载的方法,还提供了文件 上传的方法,有兴趣的读者不妨一试??用之实现一个文件上传器。 同时这个程序只是一个非常简单的例子,程序下载完一个网页后,它 所获得的仅仅是主页面的内容,并不能获得其中的图片、CSS等文 件,所以要做出一个比较好的文件下载器还需读者进一步改进之。< br>

来自:域名频道 时间:2006-9-19 返回 常见问题 首页
关于我们 联系方式 付款事宜 招聘启事 网站地图 域名注册 虚拟主机 法律顾问

Copyright 2000-2013 域名频道(www.DNS110.com)
地址:上海市松江区新松江路1188弄37号 邮编:201620
电话:021-67820741 67820742 67820743 传真:转分机805 值班电话:021-67820743
QQ:219854 Email:support@dns110.com