技巧|控制|下载
//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();
}
}
}
//定义下载类结束