2009-05-06 90 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在下载方法(在第一个语句)解决了这个问题。

谢谢

相关问题