Welcome!

Think Labs is an ongoing effort by Seven2 to provide research and educational opportunities in the web development and mobile field. To see what we’ve been cookin’ up, check out our blog postings.

Created by
Seven2 Login

Categories
Tags
Team Think Labs | Using TransmitFile() to secure downloadables
3128
single,single-post,postid-3128,single-format-standard,ajax_fade,page_not_loaded,,,wpb-js-composer js-comp-ver-4.2.3,vc_responsive
filedownload

Using TransmitFile() to secure downloadables

Sometimes you need to provide a system where users can download files from your site. This is pretty easily, up until the point where you need to gate the downloads somehow. Then you need to figure out how to send the file from the server programmatically, which is where TransmitFile() comes in.

In .Net, you’ve got a few different ways to send files from the server.

1) Response.WriteFile() – This loads the file into server memory before sending it out to the client which can cause major performance issues if the files are large, there’s a ton of usage, or both.  In almost every case, it’s just too slow and risks timeouts and other problems.

Response.WriteFile("Logo-Pale-Fireworks.png", true);

2) Response.BinaryWrite() – Sends a byte array to the browser. It’s very useful for dealing with dynamically generated files such as custom images. Or files that need to be converted from Base64 or something. You, however are on the hook for creating that byte array properly which equates to more code, which could be counter to your goals if you’re just serving static files.  It’s also much, much faster than WriteFile() (by around 1000x).

Response.BinaryWrite(byte[]);
....custom code to create byte stream...

3) Response.TransmitFile() – Doesn’t load the file into application memory making it far more efficient for the server. Super simple for static files

Response.TransmitFile( Server.MapPath("Logo-Pale-Fireworks.png") );

 

To conclude:
So, BinaryWrite if you need to do dynamic stuff, transmit if you need to do static stuff. And never Writefile because it’s awful.

Don’t be too cool like Vin Diesel because it’ll get you into trouble.