It's not strange at all - you're just misusing streams. You're assuming that a single call to Read
will read the whole of the buffer you've asked for. That's not the case - it can easily return less. You 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 the return value of Stream.Read
.
Additionally, there's no need to create a new byte array on each iteration.
Finally, if you're using .NET 4, all of this can be written much more simply:
using (var responseStream = response.GetResponseStream())
{
using (Stream file = File.Create(filePath))
{
responseStream.CopyTo(file);
}
}
(Or just use WebClient
/ HttpClient
to start with...)