Http download file exploitation (response, request) and display progress bar
Both request and response are easy to use.
/// <Summary>
/// Download an object through http
/// Current thread download
/// </Summary>
/// <Param name = "url"> Download file address </param>
/// <Param name = "buffer"> save the downloaded file to this byte array </param>
/// <Param name = "prog"> Display progress bar </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 );
}
}