2010-06-18 95 views
0

我的應用程序使用HttpWebRequest -> WebResponse -> Stream -> FileStream下載大文件。見下面的代碼。正在下載文件。網絡問題導致損壞的文件

隨着下面的場景中,我們總是得到損壞的文件:

  1. 開始下載。
  2. 拔下電纜或單擊以暫停下載過程。
  3. 關閉並打開應用程序。
  4. 開始下載(從中斷點開始)。
  5. 等待完整文件下載。

問題:下載的文件已損壞。

我確定這是常見問題,但我沒有通過搜索或搜索它。請指教。原因是什麼?

public class Downloader 
{ 
    int StartPosition { get; set; } 
    int EndPosition { get; set; } 
    bool Cancelling { get; set; } 

    void Download(string[] args) 
    { 
     string uri = @"http://www.example.com/hugefile.zip"; 
     string localFile = @"c:\hugefile.zip"; 
     HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); 
     request.AddRange(this.StartPosition); 
     WebResponse response = request.GetResponse(); 
     Stream inputStream = response.GetResponseStream(); 

     using (FileStream fileStream = new FileStream(localFile, FileMode.Open, FileAccess.Write)) 
     { 
      int buffSize = 8192; 
      byte[] buffer = new byte[buffSize]; 
      int readSize; 

      do 
      { 
       // reads the buffer from input stream 
       readSize = inputStream.Read(buffer, 0, buffSize); 

       fileStream.Position = this.StartPosition; 
       fileStream.Write(buffer, 0, (int)readSize); 
       fileStream.Flush(); 

       // increase the start position 
       this.StartPosition += readSize; 

       // check if the stream has reached its end 
       if (this.EndPosition > 0 && this.StartPosition >= this.EndPosition) 
       { 
        this.StartPosition = this.EndPosition; 
        break; 
       } 

       // check if the user have requested to pause the download 
       if (this.Cancelling) 
       { 
        break; 
       } 
      } 
      while (readSize > 0); 
     } 
    } 
} 
+0

當你比較2個文件有什麼區別?下載的部分是否缺少一部分?它是否有重複的部分或它是否有不正確的部分? – 2010-06-18 12:39:00

+0

哇!在問這個問題之前,我必須先做這件事。文件是二進制的。如何比較兩個二進制文件? – 2010-06-18 12:47:19

+0

Beyond Compare的試用版應該可以滿足您的需求。 – 2010-06-18 13:09:40

回答

1

要解決這個問題,我會建議做一個文件比較來確定差異是什麼。下載的部分是否缺少一部分?它是否有重複的部分或它是否有不正確的部分?

+0

Beyond Compare工具顯示服務器已損壞,確實不支持Accept-Ranges標頭。謝謝,馬丁! – 2010-06-18 18:12:38

1

AddRange()調用是錯誤的,你想傳遞一個負值,所以你會得到文件的其餘部分。從MSDN Library文章:

如果範圍是正數,範圍是從數據的開始到範圍。
如果範圍爲負數,範圍從範圍到數據的末尾。

我看不出EndPosition是如何初始化的,這可能也是錯誤的。

+0

我知道這個問題,我在真實的代碼中處理它。這裏的代碼並不是真正的代碼。它被剝離。謝謝。 – 2010-06-18 14:17:18

+0

不知道這意味着什麼。但AddRange調用肯定是錯誤的,並解釋了腐敗。 – 2010-06-18 14:22:43

+0

我正在使用此解決方法:http://www.codeguru.com/forum/showthread.php?t=467570 – 2010-06-18 14:55:50