OutOfMemoryException when send big file 500MB using FileStream ASPNET

前端 未结 4 820
北海茫月
北海茫月 2020-12-01 08:26

I\'m using Filestream for read big file (> 500 MB) and I get the OutOfMemoryException.

I use Asp.net , .net 3.5, win2003, iis 6.0

I want this in my app:

4条回答
  •  独厮守ぢ
    2020-12-01 09:30

    I've created download page which allows user to download up to 4gb (may be more) few months ago. Here is my working snippet:

      private void TransmitFile(string fullPath, string outFileName)
        {
            System.IO.Stream iStream = null;
    
            // Buffer to read 10K bytes in chunk:
            byte[] buffer = new Byte[10000];
    
            // Length of the file:
            int length;
    
            // Total bytes to read:
            long dataToRead;
    
            // Identify the file to download including its path.
            string filepath = fullPath;
    
            // Identify the file name.
            string filename = System.IO.Path.GetFileName(filepath);
    
            try
            {
                // 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;
    
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + outFileName);
                Response.AddHeader("Content-Length", iStream.Length.ToString());
    
                // 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 output.
                        Response.Flush();
    
                        buffer = new Byte[10000];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        //prevent infinite loop if user disconnects
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.Message);
            }
            finally
            {
                if (iStream != null)
                {
                    //Close the file.
                    iStream.Close();
                }
                Response.Close();
            }
        }
    

提交回复
热议问题