ASP.net memory usage during download

前端 未结 1 1301
一个人的身影
一个人的身影 2020-12-09 23:04

On an ASP.net site at my place of work, the following chunk of code is responsible for handling file downloads (NOTE: Response.TransmitFile is not used here because the cont

相关标签:
1条回答
  • 2020-12-09 23:58

    Here is some code that I am working on for this. It uses an 8000 byte buffer to send the file in chunks. Some informal testing on a large file showed a significant decrease in memory allocated.

    int BufferSize = 8000;
    FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    try {
      long fileSize = stream.Length;
    
      long dataLeftToRead = fileSize;
      int chunkLength;
      buffer = new Byte[BufferSize];
    
      while (dataLeftToRead > 0) {
        if (!Response.IsClientConnected) {
          break;
        }
        chunkLength = stream.Read(buffer, 0, BufferSize);
    
        Response.OutputStream.Write(buffer, 0, chunkLength);
        Response.Flush();
    
        dataLeftToRead -= chunkLength;
      }
    }
    finally {
      if (stream != null) {
        stream.Close();
    }
    

    edited to fix a syntax error and a missing value

    0 讨论(0)
提交回复
热议问题