Http download file exploitation (response, request) and display progress bar

Source: Internet
Author: User

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 );
            }
        }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.