Click here to Skip to main content
Licence CPOL
First Posted 20 Sep 2006
Views 109,786
Bookmarked 34 times

Create and download a text file from a web page

By | 12 Feb 2007 | Article
This article will demonstrate how to create a text file and view it.

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:

C#
protected void Button1_Click(object sender, EventArgs e)
{
    string sFileName = System.IO.Path.GetRandomFileName();
    string sGenName = "Friendly.txt";

    //YOu could omit these lines here as you may
    //not want to save the textfile to the server
    //I have just left them here to demonstrate that you could create the text file 
    using (System.IO.StreamWriter SW = new System.IO.StreamWriter(
           Server.MapPath("TextFiles/" + sFileName + ".txt")))
    {
        SW.WriteLine(txtText.Text);
        SW.Close();
    }

    System.IO.FileStream fs = null;
    fs = System.IO.File.Open(Server.MapPath("TextFiles/" + 
             sFileName + ".txt"), System.IO.FileMode.Open);
    byte[] btFile = new byte[fs.Length];
    fs.Read(btFile, 0, Convert.ToInt32(fs.Length));
    fs.Close();
    Response.AddHeader("Content-disposition", "attachment; filename=" + 
                       sGenName);
    Response.ContentType = "application/octet-stream";
    Response.BinaryWrite(btFile);
    Response.End();
}
VB.NET
Dim strFileName As String = System.IO.Path.GetRandomFileName()
Dim strFriendlyName As String = "Friendly.txt"

Using sw As New System.IO.StreamWriter(Server.MapPath(_
      "TextFiles/" + strFileName + ".txt"))
    sw.WriteLine(txtText.Text)
    sw.Close()
End Using

Dim fs As System.IO.FileStream = Nothing


fs = System.IO.File.Open(Server.MapPath("TextFiles/" + strFileName + _
     ".txt"), System.IO.FileMode.Open)
Dim btFile(fs.Length) As Byte
fs.Read(btFile, 0, fs.Length)
fs.Close()
With Response
    .AddHeader("Content-disposition", "attachment;filename=" & strFriendlyName)
    .ContentType = "application/octet-stream"
   .BinaryWrite(btFile)
    .End()
end with

Conclusion

Using this approach, you should be able to download all types files on Windows systems, but there are some issues with Macintosh systems. Specifically, you may not be able to download files, instead they will always open up in the browser as expected.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Three Nine Consulting

Web Developer
Three Nine Consulting
United Kingdom United Kingdom

Member

Follow on Twitter Follow on Twitter
Three Nine is an Agile IT business.
So whether you need reliable IT services or the latest equipment, Three Nine will help you get IT right.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questionايجاد فايل Pinmembersoleymani_arak20:29 2 Nov '11  
GeneralMy vote of 5 PinmemberTory Netherton11:06 29 Jun '11  
GeneralMy vote of 5 PinmemberMember 76820303:20 17 Feb '11  
Generaldowload word file using vb.net Pinmembertrimandir prajapati1:29 16 Sep '09  
QuestionDefault File Name PinmemberNamazi20:42 13 Nov '07  
AnswerRe: Default File Name Pinmembercykophysh3921:13 13 Nov '07  
QuestionRe: Default File Name PinmemberNamazi22:13 13 Nov '07  
AnswerRe: Default File Name Pinmembercykophysh3922:47 13 Nov '07  
Generaluseful article PinmemberNamazi1:41 7 Nov '07  
GeneralRe: useful article Pinmembercykophysh392:03 7 Nov '07  
GeneralMore simple Pinmemberjcparama5:52 26 Jun '07  
GeneralRe: More simple Pinmembercykophysh397:58 26 Jun '07  
Generalin VB.NET1.1 console app Pinmemberbhavna81622:38 19 Mar '07  
GeneralRe: in VB.NET1.1 console app Pinmembercykophysh3922:50 19 Mar '07  
GeneralRe: in VB.NET1.1 console app Pinmemberbhavna81623:02 19 Mar '07  
GeneralRe: in VB.NET1.1 console app Pinmemberbhavna81623:06 19 Mar '07  
what i m doing is saving the attachments on my local disk and reading it from there using streamreader.
At this place can i specify the MIME type and display it in HTML page ?If yes then How?
GeneralRe: in VB.NET1.1 console app Pinmembercykophysh3923:28 19 Mar '07  
Generalanother simple example PinmemberReynaldo Ferrer10:09 7 Mar '07  
GeneralRe: another simple example Pinmembercykophysh3921:54 7 Mar '07  
GeneralAlternative PinmemberJon Sagara10:28 20 Sep '06  
GeneralRe: Alternative Pinmembercykophysh3911:53 20 Sep '06  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 12 Feb 2007
Article Copyright 2006 by Three Nine Consulting
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid