//c#使用線程下載文件的控制技巧和缺陷
//系統(tǒng)引用//定義線程公共變量//開(kāi)始線程下載文件//中止線程下載
//系統(tǒng)引用
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;
using system.data;
//定義線程公共變量
public system.threading.thread thread001;
public system.threading.thread thread002;
//開(kāi)始線程下載文件
private void button7_click(object sender, system.eventargs e)
{
//開(kāi)始線程下載文件
downloadclass a=new downloadclass();
thread001= new thread(new threadstart(a.downloadfile));
a.strurl=textbox1.text;
a.strfilename=textbox2.text;
thread001.start();
downloadclass b=new downloadclass();
thread002= new thread(new threadstart(b.downloadfile));
b.strurl=textbox3.text;
b.strfilename=textbox4.text;
thread002.start();
}
//中止線程下載
private void button5_click(object sender, system.eventargs e)
{
//中止線程下載
thread001.abort();
thread002.abort();
messagebox.show("線程已經(jīng)中止!","警告!");
}
//定義下載文件類.線程傳參數(shù)用
public class downloadclass
{
//打開(kāi)上次下載的文件或新建文件
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)前下載文件長(zhǎ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)文件流中的當(dāng)前指針
}
else
{
fs = new system.io.filestream(strfilename,system.io.filemode.create);
lstartpos =0;
}
//打開(kāi)網(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ù)器請(qǐng)求,獲得服務(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="下載過(guò)程中出現(xiàn)錯(cuò)誤:"+ ex.tostring();
}
}
}
//定義下載類結(jié)束
新聞熱點(diǎn)
疑難解答
圖片精選