Reading from Networkstream hangs or closes the stream before reaching end


I have an intermittent problem when reading byte data from a networkstream. The stream is used for downloading a new software version for a device (G120). The file is about 500kb in size. The file is provided by a .net web api.

The code that is used for reading from the stream is basically the same as in the HttpClient example. That is:

byte[] buffer = new buffer[4096];
int read = 0;
while((read = stream.Read(buffer, 0, buffer.length)) > 0)
    //Do something with the buffer

When the problem occurs, stream.Read hangs until timeout (or sometimes returns zero before reaching the end of the stream). When lowering the sleeptime, it seems as if the problem is more likely to occur.

I have tried the same code in a .net console application without any problems.

Does anyone have any suggestion on how to avoid or at least minimize the the number of times the problem occurs?

Also, a side question. Does a stream have any sort of checksum mechanism or should I assume that the file can be corrupted? (And implement my own checksum)?

Hi. Sorry, I said that I was using an instance of the NetworkStream class but I see now that it is of type InputNetworkStreamWrapper (can’t find it in any documentation) returned by HttpWebResponse.GetResponseStream(). The Stream class does not have the DataAvailable property (which I assume is the one I should check?)

Is it possible to convert this into a NetworkStream somehow or do I have to manually create the socket and provide it to an NetworkStream instance?

Andre wrote some snippets about reading from sockets using streams: