using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.net;
using system.io;
using system.text;
using system.threading;
private void button6_click(object sender, system.eventargs e)
{
//定义一个类
//实例化一个线程对象
//实例类对象赋值
downloadclass a=new downloadclass();
thread thread2 = new thread(new threadstart(a.downloadfile));
a.strurl=textbox1.text;
a.strfilename=textbox2.text;
thread2.start();
if(thread2.join(500))
{
messagebox.show(a.strerror);
}
}
//测试用线程1断点续传下载网络上的文件到本地电脑
public class downloadclass
{
//打开上次下载的文件或新建文件
public string strurl;//文件下载网址
public string strfilename;//下载文件保存地址
public string strerror;//返回结果
public long lstartpos =0; //返回上次下载字节
public long lcurrentpos=0;//返回当前下载字节
public long ldownloadfile;//返回当前下载文件长度
public void downloadfile()
{
system.io.filestream fs;
if (system.io.file.exists(strfilename))
{
fs= system.io.file.openwrite(strfilename);
lstartpos=fs.length;
fs.seek(lstartpos,system.io.seekorigin.current);
//移动文件流中的当前指针
}
else
{
fs = new system.io.filestream(strfilename,system.io.filemode.create);
lstartpos =0;
}
//打开网络连接
try
{
system.net.httpwebrequest request =(system.net.httpwebrequest)system.net.httpwebrequest.create(strurl);
long length=request.getresponse().contentlength;
ldownloadfile=length;
if (lstartpos>0)
request.addrange((int)lstartpos); //设置range值
//向服务器请求,获得服务器回应数据流
system.io.stream ns= request.getresponse().getresponsestream();
byte[] nbytes = new byte[512];
int nreadsize=0;
nreadsize=ns.read(nbytes,0,512);
while( nreadsize >0)
{
fs.write(nbytes,0,nreadsize);
nreadsize=ns.read(nbytes,0,512);
lcurrentpos=fs.length;
}
fs.close();
ns.close();
strerror="下载完成";
}
catch(exception ex)
{
fs.close();
strerror="下载过程中出现错误:"+ ex.tostring();
}
}
}
//定义下载类结束
新闻热点
疑难解答