How to find out the length of the response (HttpWebRequest.GetResponse (). GetResponseStream ())

In any case, can I find out the length of the response stream to show the user the percentage download progress instead of the undefined?

I found that the answer looks like below, not searchable and without length

+6
source share
3 answers

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

+13
source

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

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

The ContentLength property is simply dispatched as part of the header from the server. There are situations when the server may not know the length of the response before sending the header. For example, if you are loading a dynamically generated web page with buffering disabled on the server.

+1
source

I decided to create a packaging class called WebStreamWithLenght (the search method is not implemented because I do not need it)

you should use it like this

 WebRequest req = HttpWebRequest.Create(link); WebResponse res = req.GetResponse(); var stream = res.GetResponseStream(); var streamWithLenght = new WebStreamWithLenght(stream, res.ContentLength); public class WebStreamWithLenght : Stream { long _Lenght; Stream _Stream; long _Position; public WebStreamWithLenght(Stream stream, long lenght) { _Stream = stream; _Lenght = lenght; } public override bool CanRead { get { return _Stream.CanRead; } } public override bool CanSeek { get { return true; } } public override bool CanWrite { get { return _Stream.CanWrite; } } public override void Flush() { _Stream.Flush(); } public override long Length { get { return _Lenght; } } public override long Position { get; set; } public override int Read(byte[] buffer, int offset, int count) { var result = _Stream.Read(buffer, offset, count); Position += count; return result; } public override long Seek(long offset, SeekOrigin origin) { throw new NotImplementedException(); } public override void SetLength(long value) { _Lenght = value; } public override void Write(byte[] buffer, int offset, int count) { Write(buffer, offset, count); } } 
-3
source

All Articles