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 wi开发者_如何学编程th no length
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.
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.
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
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);
}
}
精彩评论