locked
File Handler low speed RRS feed

  • Question

  • User-1925390108 posted

     I have created a custom file handler that allows users to download files. Source of the file is an external stream and I cannot use HttpResponse.TransmitFile method. Everything works fine except that the speed is low. First I was suspicious that maybe source stream is slow so I created a test application that reads a local file from server and writes it to the response stream. Here is the code that handles this:

      

        public void ProcessRequest (HttpContext context) {

    string filePath = context.Server.MapPath("~/LocalFiles/BigFile.zip");
    System.IO.FileInfo file = new System.IO.FileInfo(filePath);

    context.Response.Buffer = false;
    context.Response.AppendHeader("Content-Disposition", "attachment; filename=BigFile.zip;");
    context.Response.AddHeader("Content-Length", file.Length.ToString());
    context.Response.Flush();

    using (System.IO.Stream stream = file.OpenRead())
    {
    int size = 2048;
    byte[] data = new byte[size];
    while (true)
    {
    size = stream.Read(data, 0, data.Length);
    if (size > 0)
    {
    context.Response.OutputStream.Write(data, 0, size);

    if (!context.Response.IsClientConnected)
    break;
    }
    else { break;
    }
    }
    }

    context.Response.OutputStream.Flush();
    context.Response.OutputStream.Close();

    }

     
    I get the maximum of 150KB/s with this method but if I use TransmitFile download speed would be around 600KB/s. Here is the code when TransmitFile is used:

     

        public void ProcessRequest (HttpContext context) {

    string filePath = context.Server.MapPath("~/LocalFiles/BigFile.zip");
    System.IO.FileInfo file = new System.IO.FileInfo(filePath);

    context.Response.Buffer = false;
    context.Response.AppendHeader("Content-Disposition", "attachment; filename=BigFile.zip;");
    context.Response.AddHeader("Content-Length", file.Length.ToString());
    context.Response.Flush();

    context.Response.TransmitFile(filePath);

    }

      

    The problem is that in my case I can't use TransmitFile because I only have access to the file stream. I tried different buffer sizes but all where the same and I got even lower speeds with very big or very small buffers. 

    Wednesday, September 26, 2007 2:20 PM

Answers

  • User-143727328 posted

    My guess is that your read buffer size is a bit small. Try increasing it to something like 64k.

    UPDATED: Sorry I missed the bit at the end about you trying different buffer sizes. How big did you go?

    Kev

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, September 26, 2007 10:04 PM