c# - Strange behavior of WebReponse.GetStream -


i'm writing web downloader , have met strange problem. sample code:

 int chunk;  var request = webrequest.create(uri) httpwebrequest;    using (webresponse response = request.getresponse())   {       using (var responsestream = response.getresponsestream())       {            using (stream file = file.create(filepath))            {                long bytereaded = 0;                long contentlength = response.contentlength;                while (bytereaded < contentlength)                {                     long bytescounttoread = contentlength - bytereaded > chunk ? chunk : contentlength - bytereaded;                     byte[] buffer = new byte[bytescounttoread];                     responsestream.read(buffer, 0, buffer.length);                     file.write(buffer, 0, buffer.length);                     bytereaded += bytescounttoread;                 }             }       }   } 

problem : when 'chunk' variable == 1 or 2 bytes it's ok. when size larger - images become disturbed! i've figured out download speed(response reading speed), because when set larger size of chunk , insert thread.sleep(time) @ last line of while cycle, images stay normal. wish me.

1 byte chunk size 50 kbytes chunk size

it's not strange @ - you're misusing streams. you're assuming single call read read whole of buffer you've asked for. that's not case - can return less. should change this:

responsestream.read(buffer, 0, buffer.length); file.write(buffer, 0, buffer.length); bytereaded += bytescounttoread; 

to:

int chunkread = responsestream.read(buffer, 0, buffer.length); file.write(buffer, 0, chunkread); bytereaded += chunkread; 

you should never ignore return value of stream.read.

additionally, there's no need create new byte array on each iteration.

finally, if you're using .net 4, of can written much more simply:

using (var responsestream = response.getresponsestream()) {     using (stream file = file.create(filepath))     {         responsestream.copyto(file);     } } 

(or use webclient / httpclient start with...)


Comments

Popular posts from this blog

assembly - 8086 TASM: Illegal Indexing Mode -

Java, LWJGL, OpenGL 1.1, decoding BufferedImage to Bytebuffer and binding to OpenGL across classes -

javascript - addthis share facebook and google+ url -