2010-05-01 63 views
1

我想了解此網頁上的一些示例代碼:(http://www.csharp-station.com/HowTo/HttpWebFetch.aspx),它從Internet下載文件。下載C#示例中的網頁

下面引用的代碼段經過一個循環獲取數據塊並將它們保存爲一個字符串,直到所有數據都被下載。據我瞭解,「count」包含下載塊的大小,並且循環運行,直到count爲0(下載一個空數據塊)。

我的問題是,是不是可能計數可能是0,沒有文件被完全下載?如果網絡連接中斷,則流可能沒有任何數據要讀取循環傳遞並且計數應該爲0,從而過早結束下載。或者ResStream.Read停止該程序,直到它獲取數據?這是保存流的正確方法嗎?一旦流的末尾已到達

 
    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? 

+0

MSDN示出了一個相同的樣品:http://msdn.microsoft.com/en-us/library/system.net.webresponse .getresponsestream.aspx – M4N 2010-05-01 21:43:04

回答

3

Stream.Read只會返回0。呼叫將被阻塞,直到有數據可用或連接已關閉。

該代碼將工作,因爲它是,但也可以簡化爲:

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); 
} 
+0

Aha。謝謝。 – Chris 2010-05-01 21:46:14