2011-04-05 252 views
0

嗨,此功能從源下載圖像並將其添加到zip文件。 問題有時出現的圖像全部搞砸了(1/3下載,其餘是空的空間),好像下載沒有完成。我如何確保在我繼續之前完成下載?謝謝。等待webrequest完成

編輯:我有超時,所以它不會無限期地等待。我應該延長超時時間嗎?或者,還有更好的方法?

public void addImage(string source, string destination) 
    { 
     if (isFinalized) 
      return; 

     try 
     { 
      WebRequest req = WebRequest.Create(source); 
      req.Timeout = 5000; 

      WebResponse resp = req.GetResponse(); 
      BufferedStream reader = new BufferedStream(resp.GetResponseStream()); 

      byte[] fileData = new byte[resp.ContentLength]; 
      reader.Read(fileData, 0, fileData.Length); 
      zip.AddEntry(destination, fileData); 
     } 
     catch (Exception exp) 
     { 
     } 
    } 
+0

擺脫try/catch,對於初學者。你怎麼知道你沒有看到異常? – 2011-04-05 20:30:19

回答

1

在你的代碼,你需要檢查readed字節,並查看是否已完全得到你的形象。

int FinalRead = reader.Read(fileData, 0, fileData.Length); 
bool fImageIsOk = FinalRead == resp.ContentLength ; 

此外,我強烈建議以翹曲BufferedStreamusing

我認爲,在msdn have a good example示例代碼。

你必須關注的部分是這個。不要試圖找到你的緩衝區。最後,你可以檢查你是否已經收到你的照片。您還可以檢查其他部分是否仍在連接進程IsClientConnected

int numBytesToRead = receivedData.Length; 

while (numBytesToRead > 0) 
{ 
    // Read may return anything from 0 to numBytesToRead. 
    int n = bufStream.Read(receivedData,0, receivedData.Length); 
    // The end of the file is reached. 
    if (n == 0) 
     break; 
    bytesReceived += n; 
    numBytesToRead -= n; 
}