会员
周边
众包
新闻
博问
闪存
所有博客
当前博客
我的博客
我的园子
账号设置
简洁模式
...
退出登录
注册
登录
Nice感觉
海绵不断的吸收
博客园
首页
新随笔
联系
订阅
管理
利用线程下载网页中的程序并另存到本地(转载收藏)
前台页面要输入下载地址和另存路径
private
void
BtnDown_Click(
object
sender, System.EventArgs e)
{
//
开始线程下载文件
DownloadClass downFile
=
new
DownloadClass();
downThread
=
new
Thread(
new
ThreadStart(downFile.DownloadFile));
downFile.StrUrl
=
txtFromUrl.Text;
downFile.StrFileName
=
txtSavePath.Text;
downThread.Start();
}
DownloadClass.cs (注意命名空间哦。)
下载并保存下载文件的类
using
System;
using
System.IO;
using
System.Net;
namespace
HGJ.DBA
{
/**/
///
<summary>
///
DownloadClass 的摘要说明。
///
</summary>
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();
//
这里可直接将获取到的下载数据存入数据库,传递:nbytes 即可对应Image类型
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();
}
}
}
}
posted on
2007-05-09 09:45
Gary.han
阅读(
368
) 评论(
0
)
编辑
收藏
举报
会员力量,点亮园子希望
刷新页面
返回顶部