Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know the length of Response (HttpWebRequest.GetResponse().GetResponseStream())

Any way I can know the length of the response stream so I can show the user a percentage progress of download instead of an indeterminate one?

I find that the Response looks like below, non seekable and with no length

like image 798
Jiew Meng Avatar asked Nov 22 '10 03:11

Jiew Meng


People also ask

How do I read Httpwebresponse response?

If you call the GetRequestStream method, you must use the GetResponse method to retrieve the response. If a WebException is thrown, use the Response and Status properties of the exception to determine the response from the server.

What is HttpWebRequest C#?

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.


2 Answers

Try using the WebResponse.ContentLength property. If returns -1, it means that the remote server is not sending you the length of the response body, and therefore you cannot determine the length of the response without reading it in its entirety.

like image 89
cdhowie Avatar answered Nov 14 '22 23:11

cdhowie


If you are interested, I have a code reference library that includes a WebHelper class. It's similar to the WebClient class (including the ability to report progress), but is more flexible. It is stored on CodePlex, the project name is BizArk.

It uses the Response.ContentLength property to determine the length of the response.

The ContentLength property is simply sent as part of the header from the server. There are situations where the server may not know the length of the response prior to sending the header. For example, if you are downloading a dynamically generated webpage with the buffering turned off on the server.

like image 20
Brian Avatar answered Nov 15 '22 00:11

Brian