Permalink
Browse files

Icon: Don't rely on ContentLength but iterate over the response stream

This fixes the issues in the previous commit: we might allocate way too
much memory, and we were not sure to get the whole response. Thanks to
Gonzalo Paniagua Javier for pointing them out.
  • Loading branch information...
1 parent a05d095 commit 62787126ab4e270a31f69d9eb234ae51ecdc9a38 @bl8 bl8 committed Apr 21, 2012
Showing with 10 additions and 8 deletions.
  1. +10 −8 src/Mono.Upnp/Mono.Upnp/Mono.Upnp/Icon.cs
@@ -137,16 +137,18 @@ public virtual byte[] GetData ()
try {
var request = (HttpWebRequest)WebRequest.Create (Url);
using (var response = Helper.GetResponse (request)) {
- int response_length;
- if (response.ContentLength < 1 || response.ContentLength > Int32.MaxValue) {
- response_length = Int32.MaxValue;
- } else {
- response_length = (int)response.ContentLength;
- }
- data = new byte[response_length];
+ var ms = new MemoryStream ();
+ long bytes_read = 0;
using (var stream = response.GetResponseStream ()) {
- stream.Read (data, 0, response_length);
+ byte [] buffer = new byte[8192];
+ int chunk_bytes_read = 0;
+
+ while ((chunk_bytes_read = stream.Read (buffer, 0, buffer.Length)) > 0) {
+ ms.Write (buffer, 0, chunk_bytes_read);
+ bytes_read += chunk_bytes_read;
+ }
}
+ data = ms.ToArray ();
}
} catch (WebException e) {
if (e.Status == WebExceptionStatus.Timeout) {

0 comments on commit 6278712

Please sign in to comment.