HttpWebRequest download file, garbled problem solution

Source: Internet
Author: User

Write in front

Today the reason to summarize HttpWebRequest download file, mainly because in the use of this class to download files, some places need to pay attention to, in the actual project encountered this problem, I think it is necessary to summarize. When downloading a file, the most common is that the downloaded file is garbled.

An example

Let's take the example of the restful interface described earlier, and now I'm going to download the picture through the HttpWebRequest request.

The API address is: http://localhost:21074/ImageService/api/1.jpg

For more information on RESTful imageservice, please refer to the previous section, where only the key code is posted:

        /// <summary>        ///take a file stream based on the picture name/// </summary>        /// <param name= "Imgurl" ></param>        /// <returns></returns>         PublicSystem.IO.Stream Getimagestream (stringImgurl) {            varContentType = Path.getextension (Imgurl). Trim ('.'); Weboperationcontext WOC=weboperationcontext.current; //dynamically set contenttype based on the requested picture typeWoC. Outgoingresponse.contenttype ="image/"+ContentType; stringSavepath = System.Web.HttpContext.Current.Server.MapPath ("/images"); stringFilePath =Path.Combine (Savepath, Imgurl); returnFile.openread (FilePath); }

Client request Code

Uri URL =NewUri ("http://localhost:21074/ImageService/api/1.jpg"); HttpWebRequest Request=(HttpWebRequest) httpwebrequest.create (URL); using(Stream stream =request. GetResponse (). GetResponseStream ()) {//file stream, stream information read into file stream, finish reading off                using(FileStream fs = File.create (@"download.jpg"))                {                    //Create a byte group and set its size to how many bytes                    intLength =1024x768;//buffer, 1KB, if the settings are too large, and the size of the file to be downloaded is smaller than this value, there will be garbled.                     byte[] bytes =New byte[length]; intn =1;  while(N >0)                    {                        //How many bytes are read from the stream at a time, and assign the value to N, when it is finished, n is 0 and exits the loopn = stream. Read (Bytes,0, length); Fs. Write (Bytes,0, n);//writes the stream information of the specified bytes to the file stream                    }                }            }

Note that here at the time of reading, set the buffer 1kb, although the degree of slow, but to ensure the correctness of the data, such as if set 10KB, and the file size is less than this number, in the stream. Read, it will read too many bytes, resulting in garbled, if before downloading, can get the size of the file information, can dynamically set the size of this buffer.

Summarize

Here is the main summary, a problem encountered in the project. I hope to be of some help to you.

HttpWebRequest download file, garbled problem solution

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.