http 下载文件利用(response,request) 并显示进度条
request 和 response 都比较好用
///
/// http 下载文件
/// current thread download
///
/// 下载文件地址
/// 将下载的文件存入该字节数组
/// 用于显示的进度条
public void downloadfile(string url, ref byte[] buffer, progressbar prog)
{
try
{
system.net.httpwebrequest myrq = (system.net.httpwebrequest)system.net.httpwebrequest.create(url);
system.net.httpwebresponse myrp = (system.net.httpwebresponse)myrq.getresponse();
long totalbytes = myrp.contentlength;
if (prog != null)
{
prog.maximum = (int)totalbytes;
}
using (memorystream ms = new memorystream((int)totalbytes))
{
stream st = myrp.getresponsestream();
long totaldownloadedbyte = 0;
byte[] by = new byte[1024];
int osize = st.read(by, 0, (int)by.length);
while (osize > 0)
{
totaldownloadedbyte = osize + totaldownloadedbyte;
system.windows.forms.application.doevents();
ms.write(by, 0, osize);
if (prog != null)
{
prog.value = (int)totaldownloadedbyte;
}
osize = st.read(by, 0, (int)by.length);
}
buffer = ms.toarray();
st.close();
}
}
catch (exception ex)
{
buffer = null;
console.writeline(ex.message);
}
}