tags:

views:

57

answers:

1

I am trying to understand some example code on this web page: (http://www.csharp-station.com/HowTo/HttpWebFetch.aspx) that downloads a file from the internet.

The piece of code quoted below goes through a loop getting chunks of data and saving them to a string until all the data has been downloaded. As I understand it, "count" contains the size of the downloaded chunk and the loop runs until count is 0 (an empty chunk of data is downloaded).

My question is, isn't it possible that count could be 0 without the file being completely downloaded? Say if the network connection is interrupted, the stream may not have any data to read on a pass of the loop and count should be 0, ending the download prematurely. Or does ResStream.Read stop the program until it gets data? Is this the correct way to save a stream?

    int count = 0;

      do
      {
       // fill the buffer with data
       count = resStream.Read(buf, 0, buf.Length);

       // make sure we read some data
       if (count != 0)
       {
        // translate from bytes to ASCII text
        tempString = Encoding.ASCII.GetString(buf, 0, count);

        // continue building the string
        sb.Append(tempString);
       }
      }
      while (count > 0); // any more data to read?

+3  A: 

Stream.Read will only return 0 once the end of the stream has been reached. The Read call will block until there is data available or the connection has been closed.

The code will work as it is, but could be simplified:

int count;

while ((count = resStream.Read(buf, 0, buf.Length)) > 0)
{
    // translate from bytes to ASCII text
    string tempString = Encoding.ASCII.GetString(buf, 0, count);

    // continue building the string
    sb.Append(tempString);
}
Phil Ross
Aha. Thank you.
Chris