技巧|控制|下載
//c#使用線程下載檔案的控制技巧和缺陷
//系統引用//定義線程公開變數//開始線程下載檔案//中止線程下載
//系統引用
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;
//開始線程下載檔案
private void button7_Click(object sender, System.EventArgs e)
{
//開始線程下載檔案
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("線程已經中止!","警告!");
}
//定義下載檔案類.線程傳參數用
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();
}
}
}
//定義下載類結束