Click here to Skip to main content
12,510,224 members (54,931 online)
Click here to Skip to main content
Add your own
alternative version

Stats

217.3K views
94 downloads
37 bookmarked
Posted

Create and download a text file from a web page

, 12 Feb 2007 CPOL
Rate this:
Please Sign up or sign in to vote.
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)

Share

About the Author

Three Nine Consulting
Web Developer Three Nine Consulting
United Kingdom United Kingdom
A freelance software developer in the UK with over 12+ years software development experience. My fascination and passion for software development, technology and business has set me on a lifetime course of continual learning and self improvement. I value feedback, regardless whether it is negative or positive, it is one of the primary sources of inspiration to improve!

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralGood function! Pin
Alan Oliveira23-Jun-15 7:52
memberAlan Oliveira23-Jun-15 7:52 
QuestionHow to apply Styles to word file in asp.net Pin
Member 1143216616-Jun-15 1:04
memberMember 1143216616-Jun-15 1:04 
QuestionHow to apply Styles to word file from web page Pin
Member 1143216616-Jun-15 1:03
memberMember 1143216616-Jun-15 1:03 
GeneralThanks! Pin
xiaoyintao27-Oct-14 16:47
memberxiaoyintao27-Oct-14 16:47 
GeneralThanks! Pin
Manoj Nathwani19-Feb-13 11:40
memberManoj Nathwani19-Feb-13 11:40 
Generalwonderful! Pin
Janilane22-Aug-12 0:37
memberJanilane22-Aug-12 0:37 
Questionايجاد فايل Pin
soleymani_arak2-Nov-11 20:29
membersoleymani_arak2-Nov-11 20:29 
GeneralMy vote of 5 Pin
Tory Netherton29-Jun-11 11:06
memberTory Netherton29-Jun-11 11:06 
GeneralRe: My vote of 5 Pin
Three Nine Consulting20-Mar-13 1:39
memberThree Nine Consulting20-Mar-13 1:39 
GeneralMy vote of 5 Pin
Member 768203017-Feb-11 3:20
memberMember 768203017-Feb-11 3:20 
Generaldowload word file using vb.net Pin
trimandir prajapati16-Sep-09 1:29
membertrimandir prajapati16-Sep-09 1:29 
QuestionDefault File Name Pin
Namazi13-Nov-07 20:42
memberNamazi13-Nov-07 20:42 
AnswerRe: Default File Name Pin
cykophysh3913-Nov-07 21:13
membercykophysh3913-Nov-07 21:13 
QuestionRe: Default File Name Pin
Namazi13-Nov-07 22:13
memberNamazi13-Nov-07 22:13 
AnswerRe: Default File Name Pin
cykophysh3913-Nov-07 22:47
membercykophysh3913-Nov-07 22:47 
Generaluseful article Pin
Namazi7-Nov-07 1:41
memberNamazi7-Nov-07 1:41 
GeneralRe: useful article Pin
cykophysh397-Nov-07 2:03
membercykophysh397-Nov-07 2:03 
GeneralMore simple Pin
jcparama26-Jun-07 5:52
memberjcparama26-Jun-07 5:52 
GeneralRe: More simple Pin
cykophysh3926-Jun-07 7:58
membercykophysh3926-Jun-07 7:58 
Generalin VB.NET1.1 console app Pin
bhavna81619-Mar-07 22:38
memberbhavna81619-Mar-07 22:38 
GeneralRe: in VB.NET1.1 console app Pin
cykophysh3919-Mar-07 22:50
membercykophysh3919-Mar-07 22:50 
GeneralRe: in VB.NET1.1 console app Pin
bhavna81619-Mar-07 23:02
memberbhavna81619-Mar-07 23:02 
GeneralRe: in VB.NET1.1 console app Pin
bhavna81619-Mar-07 23:06
memberbhavna81619-Mar-07 23:06 
GeneralRe: in VB.NET1.1 console app Pin
cykophysh3919-Mar-07 23:28
membercykophysh3919-Mar-07 23:28 
Generalanother simple example Pin
Reynaldo Ferrer7-Mar-07 10:09
memberReynaldo Ferrer7-Mar-07 10:09 
GeneralRe: another simple example Pin
cykophysh397-Mar-07 21:54
membercykophysh397-Mar-07 21:54 
GeneralAlternative Pin
Jon Sagara20-Sep-06 10:28
memberJon Sagara20-Sep-06 10:28 
GeneralRe: Alternative Pin
cykophysh3920-Sep-06 11:53
membercykophysh3920-Sep-06 11:53 

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

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

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