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斷點續(xù)傳下載網(wǎng)絡(luò)上的文件到本地電腦
public class downloadclass
{
//打開上次下載的文件或新建文件
public string strurl;//文件下載網(wǎng)址
public string strfilename;//下載文件保存地址
public string strerror;//返回結(jié)果
public long lstartpos =0; //返回上次下載字節(jié)
public long lcurrentpos=0;//返回當(dāng)前下載字節(jié)
public long ldownloadfile;//返回當(dāng)前下載文件長度
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);
//移動文件流中的當(dāng)前指針
}
else
{
fs = new system.io.filestream(strfilename,system.io.filemode.create);
lstartpos =0;
}
//打開網(wǎng)絡(luò)連接
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); //設(shè)置range值
//向服務(wù)器請求,獲得服務(wù)器回應(yīng)數(shù)據(jù)流
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="下載過程中出現(xiàn)錯誤:"+ ex.tostring();
}
}
}
//定義下載類結(jié)束
新聞熱點
疑難解答
圖片精選