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