Serving large files with C# HttpListener

后端 未结 1 1285
暗喜
暗喜 2020-12-08 16:49

I\'m trying to use HttpListener to serve static files, and this works well with small files. When file sizes grow larger (tested with 350 and 600MB files), the server chokes

相关标签:
1条回答
  • 2020-12-08 17:19

    You didn't show us the other critical part how you initialized HttpListener. Therefore I tried your code with the one below and it worked

    HttpListener listener = new HttpListener();
    listener.Prefixes.Add("http://*:8080/");
    listener.Start();
    Task.Factory.StartNew(() =>
    {
        while (true)
        {
            HttpListenerContext context = listener.GetContext();
            Task.Factory.StartNew((ctx) =>
            {
                WriteFile((HttpListenerContext)ctx, @"C:\LargeFile.zip");
            }, context,TaskCreationOptions.LongRunning);
        }
    },TaskCreationOptions.LongRunning);
    

    WriteFile is your code where Thread.Sleep( 200 ); is removed.

    If you want to see the full code of it.


    void WriteFile(HttpListenerContext ctx, string path)
    {
        var response = ctx.Response;
        using (FileStream fs = File.OpenRead(path))
        {
            string filename = Path.GetFileName(path);
            //response is HttpListenerContext.Response...
            response.ContentLength64 = fs.Length;
            response.SendChunked = false;
            response.ContentType = System.Net.Mime.MediaTypeNames.Application.Octet;
            response.AddHeader("Content-disposition", "attachment; filename=" + filename);
    
            byte[] buffer = new byte[64 * 1024];
            int read;
            using (BinaryWriter bw = new BinaryWriter(response.OutputStream))
            {
                while ((read = fs.Read(buffer, 0, buffer.Length)) > 0)
                {
                    bw.Write(buffer, 0, read);
                    bw.Flush(); //seems to have no effect
                }
    
                bw.Close();
            }
    
            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";
            response.OutputStream.Close();
        }
    }
    
    0 讨论(0)
提交回复
热议问题