2009-05-06 92 views
21

此碼流大文件到我們的用戶:「遠程主機關閉了連接」中Response.OutputStream.Write

   // Open the file. 
      iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, 
         System.IO.FileAccess.Read, System.IO.FileShare.Read); 


      // Total bytes to read: 
      dataToRead = iStream.Length; 

      // Read the bytes. 
      while (dataToRead > 0) 
      { 
       // Verify that the client is connected. 
       if (Response.IsClientConnected) 
       { 
        // Read the data in buffer. 
        length = iStream.Read(buffer, 0, 10000); 

        // Write the data to the current output stream. 
        Response.OutputStream.Write(buffer, 0, length); 

        // Flush the data to the HTML output. 
        Response.Flush(); 

        buffer = new Byte[10000]; 
        dataToRead = dataToRead - length; 
       } 
       else 
       { 
        //prevent infinite loop if user disconnects 
        dataToRead = -1; 
       } 
      } 

每一次,一段時間,我們收到這個異常:

The remote host closed the connection. The error code is 0x80072746 

以下是完整的堆棧跟蹤:

Stack Trace: 
    at System.Web.Hosting.ISAPIWorkerRequestInProcForIIS6.FlushCore(Byte[] status, Byte[] header, Int32 keepConnected, Int32 totalBodySize, Int32 numBodyFragments, IntPtr[] bodyFragments, Int32[] bodyFragmentLengths, Int32 doneWithSession, Int32 finalStatus, Boolean& async) 
    at System.Web.Hosting.ISAPIWorkerRequest.FlushCachedResponse(Boolean isFinal) 
    at System.Web.Hosting.ISAPIWorkerRequest.FlushResponse(Boolean finalFlush) 
    at System.Web.HttpResponse.Flush(Boolean finalFlush) 
    at System.Web.HttpResponse.Flush() 
    at System.Web.HttpWriter.WriteFromStream(Byte[] data, Int32 offset, Int32 size) 
    at System.Web.HttpResponseStream.Write(Byte[] buffer, Int32 offset, Int32 count) 
    at BIS.DocumentBus.Controls.DocumentViewer.StreamFile(String filepath) 

我們從未有過的證據表明,用戶無法下載我們的文件並計劃簡單地忽略這個例外。

任何想法這個問題的根源是什麼?可以忽略嗎?

+0

可能重複[遠程主機關閉連接。錯誤代碼是0x800704CD](http://stackoverflow.com/questions/5564862/the-remote-host-closed-the-connection-the-error-code-is-0x800704cd) – 2017-03-22 06:22:34

回答

17

該異常意味着下載文件的客戶端在文件下載完成之前破壞了連接。即客戶端導航到另一個頁面,或者只是關閉瀏覽器。

我可能會嘗試移動if (Response.IsClientConnected)行後iStream.Read。即使你這樣做了,我認爲如果在OutputStream.Write方法仍在工作時連接中斷,仍然可能會收到此錯誤。

+3

我從來沒有能夠重現異常通過取消下載。我們甚至試圖在下載過程中斷開我們的網絡連接。也沒有引起例外情況發生。 – spaetzel 2009-05-06 20:37:39

12

這有幾個不同的可能原因。我可以想到三個:

一個是填充緩衝區接近2GB的數據,但這不應該在這裏,因爲你經常沖洗。

另一個確實是在你之前接受的答案中描述的。複製非常困難,所以我不會認爲這是錯誤的。

另一種可能的情況,我敢打賭,是executionTimeout被超過,這將首先導致ThreadAbortException,但這可能會導致Flush()失敗,這將變成異常記錄

4

在web.config的httpRuntime元素中增加executionTimeout。

如果用戶正在慢速連接下載大文件,請求最終會超時。

2

我發佈了這個答案,因爲它可能會幫助別人,並節省一些重要的時間。

在我的情況下,Response.Buffer = true在下載方法(在第一個語句)解決了這個問題。

謝謝

相關問題