Tomas
Tomas

Reputation: 775

How do I optimise file downloads in ASP.NET?

I have ASP.NET application which allows users to download a file when he/she enters a password. I use code below to send file to user:

Context.Response.Clear();
Context.Response.ContentType = "application/pdf";
Context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Context.Response.BinaryWrite(File.ReadAllBytes(fileName));
Context.Response.Flush();
Context.Response.Close();   

The problem is that the downloads become very slow if the files are more than 1mb or many users are downloading files at the same time. Is it possible somehow to optimize code for better performance?

Upvotes: 0

Views: 615

Answers (2)

philipproplesch
philipproplesch

Reputation: 2127

You might use Response.TransmitFile(/* Your file */); instead of Response.BinaryWrite(/* Your file */);

The TransmitFile()-Method writes the data to the HTTP output stream without storing it in the memory.

Upvotes: 2

Mark Brittingham
Mark Brittingham

Reputation: 28875

Why are you managing the downloads manually? Why not just put a link to the appropriate PDF file on the page that is shown after a successful login? This will free up the ASP.NET threads so you don't use them to manage the file download. IIS will still have to serve them up but I think it would reduce your overhead significantly.

Are you worried about the file name being exposed? If so, reply - there are a few other options you can explore.

Upvotes: 1

Related Questions