简体   繁体   中英

How to perform a download instantly with ASP.NET C#?

We have a rather large amount of data to be downloaded.

Currently our system just outputs the stream (we do not use files)

Code:

HttpContext.Current.Response.AppendHeader("content-disposition", String.Format("attachment; filename={0}", filename));
            HttpContext.Current.Response.BinaryWrite(ms.ToArray());

            HttpContext.Current.Response.End();

However, it is using an extensive amount of memory on the server, waiting for the file to download.. I'd like to make it so it starts to download immediately rather than waiting... How can I do this?

the problem is the MemoryStream.ToArray method which puts the whole content in the web server memory.

you should pass the memory stream differently to the BinaryWrite so you can profit from buffering and stream down data to the client without requiring too much memory.

Rather than convert the entire download into an Array you should copy the data straight from the source stream to the destination stream.

See Best way to copy between two Stream instances - C# for a good way of copying between streams.

From a guess ms is a memory stream, and so the following should do the trick:

CopyStream(ms, HttpContext.Current.Response.OutputStream);

Better yet would be to write directly to the output stream rather than to the intermediate stream, however how you do this depends on how you got the data contained in ms .

尝试设置:

HttpContext.Current.Response.BufferOutput = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM