...Because someone's gotta tell the story...


To return to the main Blog List, click Full Blog Listing.



Downloading files in ASP.NET

Friday, June 20, 2008 in Technical Articles (Views: 6500)
Today's blog, powered by VB.NET, is sponsored by the response.binarywrite command.

It's been a while since I've made any updates to the actual site, but I will be adding file attachments to the blogs. This below is the code how (I am also adding in file download code to the blog pages as well)

It seems to be a bad practice anymore to allow users to download files using the good old fashioned HTML tag, so here's a little source code I am using which allows users to download files from ASP.NET (written in VB.NET).

If you would like to test, simply put this code in a Page_Load.
'This code needs no additional namespaces

Dim strFileName As String = System.IO.Path.GetRandomFileName()

Dim strFriendlyName As String = "textfile.txt"

Dim fs As System.IO.FileStream = Nothing

'The path is relative to the website, for example, I will use downloads. We create the data stream here...

fs = System.IO.File.Open(Server.MapPath("downloads/" + strFriendlyName), System.IO.FileMode.Open)

Dim btFile(CInt(fs.Length)) As Byte

fs.Read(btFile, 0, CInt(fs.Length))


'Set up for the download, with BinaryWrite being the money shot...

With Response

.AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)

.ContentType = "application/octet-stream"



End With
This will send the file ../download/textfile.txt to the user.


Related Blogs You May Be Interested In:

To leave a comment, please log in and/or register.