2013-04-04 100 views
0

下面是我的代碼來下載文件。下載非常大的文件會導致客戶端每隔1:30-1:45分鐘斷開連接

   Stream iStream = null; 

      // Buffer to read 1K bytes in chunk: 
      byte[] buffer = new Byte[ 4194304 ]; 

      // Length of the file: 
      int length; 

      // Total bytes to read: 
      long dataToRead; 

      // Identify the file to download including its path. 
      string filepath = PathToFile; 

      // Identify the file name. 
      //string filename = Path.GetFileName(filepath); 
          Response.Clear(); 
      try 
      { 
       // Open the file. 
       iStream = new FileStream(filepath, FileMode.Open, 
          FileAccess.Read, FileShare.Read); 


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

       Response.ContentType = ContentType; 
       Response.AddHeader("Content-Disposition", "attachment; filename=" + clientNameOfFile); 
       Response.AddHeader("Content-Length", dataToRead.ToString()); 

       Response.BufferOutput = true; 
       // 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, 100000); 

         // 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[ 100000]; 
         dataToRead = dataToRead - length; 
        } 
        else 
        { 
         //prevent infinite loop if user disconnects 
         dataToRead = -1; 
        } 
       } 
      } 
      catch (Exception ex) 
      { 
       // Trap the error, if any. 
       Response.Write("Error : " + ex.Message); 

      } 
      finally 
      { 
       if (iStream != null) 
       { 
        //Close the file. 
        iStream.Close(); 
       } 
       Response.Close(); 
      } 

當試圖下載50MB文件時,客戶端在每1:30到1:45分鐘後斷開連接。我應該檢查哪些可能導致客戶端斷開連接的一些事情?

I have the following web config settings 
<httpRuntime executionTimeout="999999" maxRequestLength="51200" /> 
<sessionState mode="StateServer" stateConnectionString="xxx:42424" useHostingIdentity="true" timeout="10000" /> 
<requestFiltering> 
      <requestLimits maxAllowedContentLength="209715200" /> 
     </requestFiltering> 

的IIS應用程序池空閒超時設置爲20

+0

我認爲這是代碼的服務器端,你如何下載文件?你使用C#客戶端還是Web客戶端等? – SynerCoder 2013-04-04 15:48:18

+0

我們不使用任何Web客戶端。直接將數據寫入瀏覽器 – user2221069 2013-04-04 15:52:56

+0

如果您使用'Stream.CopyTo',您的代碼將更加簡單明瞭。 – 2013-04-04 16:01:09

回答

0

你在你的代碼不一致。你已經聲明瞭byte [] buffer = new Byte [4194304];在開始時將其更改爲buffer = new Byte [100000];在while循環中。長度也不一致,長度= iStream.Read(buffer,0,100000);

相關問題