http 下载文件利用(response,request) 并显示进度条
request 和 response 都比较好用
/// <summary>
/// http 下载文件
/// current thread download
/// </summary>
/// <param name="url">下载文件地址</param>
/// <param name="buffer">将下载的文件存入该字节数组</param>
/// <param name="prog">用于显示的进度条</param>
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);
}
}