Introduction It is often a common requirement in a web application to have the ability to download some sort of file to the client's computer. This article will illustrate how to create and download a text file to the user's computer. Using the code Although in the example I actually create the text file before I stream it out to the client, I feel it is important to highlight that you don't necessarily have to do this, as the file could actually exist on the file system and you may want to stream it out to the client.
If that is the case, you may need to use FileStream to read the already existing document. We first open the file for reading and we actually read the file byte for byte into a stream, then once we have the file into a stream, we then just use the Response object and download the file via the output stream. Response.AddHeader( ' Content-disposition', ' attachment; filename=' + sGenName); Response.ContentType = ' application/octet-stream'; Response.BinaryWrite(btFile); Response.End(); The real power in this snippet is in the lines above; by adding a header, you are telling the browser to download the file as an attachment. Then you set the ContentType header which is added, and set your MIME type so that the browser knows what kind of file it is about to download. You can choose any of the following MIME types for the browser: '.asf' = 'video/x-ms-asf' '.avi' = 'video/avi' '.doc' = 'application/msword' '.zip' = 'application/zip' '.xls' = 'application/vnd.ms-excel' '.gif' = 'image/gif' '.jpg'= 'image/jpeg' '.wav' = 'audio/wav' '.mp3' = 'audio/mpeg3' '.mpg' 'mpeg' = 'video/mpeg' '.rtf' = 'application/rtf' '.htm', 'html' = 'text/html' '.asp' = 'text/asp' 'Handle All Other Files = 'application/octet-stream' A full example of how to go about downloading a text file would like the code below. Jarvis 758 444f 7-Mar-07 11:09 7-Mar-07 11:09 'a simple text With Response.AddHeader('Content-disposition', 'attachment;filename=myText.txt').ContentType = 'application/octet-stream'.BinaryWrite(System.Text.UTF8Encoding.UTF8.GetBytes('Hello World!!!'