using system;
using system.drawing;
using system.collections;
using system.componentmodel;
using system.windows.forms;
using system.net;
using system.io;
using system.text;
private void button3_click(object sender, system.eventargs e)
{
string downloadurl=textbox3.text;
string localpath=textbox4.text;
if(downfile(downloadurl,localpath))
{
messagebox.show("下载完成");
}
else
{
messagebox.show("下载过程中出现错误:");
}
}
public bool downfile(string url,string localpath)
{
try
{
uri u = new uri(url);
httpwebrequest mrequest = (httpwebrequest)webrequest.create(u);
mrequest.method = "get";
mrequest.contenttype = "application/x-www-form-urlencoded";
httpwebresponse wr = (httpwebresponse)mrequest.getresponse();
stream sin = wr.getresponsestream();
filestream fs = new filestream(localpath, filemode.create, fileaccess.write);
long length = wr.contentlength;
long i = 0;
decimal j=0;
while (i < length)
{
byte[] buffer = new byte[1024];
i += sin.read(buffer, 0, buffer.length);
fs.write(buffer, 0, buffer.length);
if((i % 1024)==0)
{
j=math.round(convert.todecimal((convert.todouble(i)/convert.todouble(length))*100),4);
statusbar1.text="当前下载文件大小:"+length.tostring()+"字节 当前下载大小:"+i+"字节 下载进度"+j.tostring()+"%";
}
else
{
statusbar1.text="当前下载文件大小:"+length.tostring()+"字节 当前下载大小:"+i+"字节";
}
}
sin.close();
wr.close();
fs.close();
return true;
}
catch { return false; }
}
新闻热点
疑难解答