c#使用线程下载文件的控制技巧和缺陷

//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();

}

}
} 
//定义下载类结束

阅读终点,创作起航,您可以撰写心得或摘录文章要点写篇博文。去创作
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值