如何知道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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试使用
WebResponse.ContentLength
属性。如果返回-1,则意味着远程服务器没有向您发送响应正文的长度,因此您无法在不完整读取响应的情况下确定响应的长度。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.如果您有兴趣,我有一个代码参考库,其中包含 WebHelper 类。它类似于 WebClient 类(包括报告进度的能力),但更灵活。它存储在CodePlex上,项目名称为BizArk。
它使用 Response.ContentLength 属性来确定响应的长度。
ContentLength 属性只是作为标头的一部分从服务器发送。在某些情况下,服务器在发送标头之前可能不知道响应的长度。例如,如果您正在下载动态生成的网页,并且服务器上的缓冲已关闭。
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.
我解决了创建一个名为WebStreamWithLenght的包装类(未实现seek方法,因为我不需要它)
你应该像这样使用它
i solved creating a wrapping class named WebStreamWithLenght (the seek method is not implemented because i didn't need it)
you should use it like this