5,664,339 members and growing! (17,444 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner

Create and download text file from a web page

By Three Nine Consulting

This article will demonstrate how to create a text file and view it in
C#, VB, Windows, .NET 2.0, .NET, WebForms, ASP.NET, Visual Studio, VS2005, Dev

Posted: 20 Sep 2006
Updated: 12 Feb 2007
Views: 36,766
Bookmarked: 17 times
Announcements
Loading...



Search    
Advanced Search
Sitemap
7 votes for this Article.
Popularity: 1.89 Rating: 2.24 out of 5
3 votes, 42.9%
1
1 vote, 14.3%
2
1 vote, 14.3%
3
1 vote, 14.3%
4
1 vote, 14.3%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

It is often a common requirement in a web application to have the ability to download a some sort of file to the clients computer. This article will illustrate how to create and download a text file to the users 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 one need to use the FileStream to read the already existing document.

We first open the file for reading and we actually read the file byte for byte into stream, then once we have the file into a stream, we basically 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 header, you are telling the browser to download the file as an attachment. Then you set The ContentType header which is added, sets your MIME type so that the browser knows what kind of file it is about to download. One 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 could 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 files on Windows systems, but there are some issues with Macintosh systems. Specifically, you may not be able to download the files, instead they will always open up in the browser as expected.

References

Downloading and uploading files

Send an attachment to the browser

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Three Nine Consulting


Over 15 years experience in the IT industry, in which acquiring numerous skills from the various sectors ,over the past 8 years concentrated mainly developing business Information systems. Skilled in a number of programming languages including C++ ,Java, Visual Basic but laterly focused on C# and VB.net.

Visit Gary's website is www.threenine.co.uk
for more details
Occupation: Web Developer
Company: Three Nine Consulting
Location: United Kingdom United Kingdom

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 17 of 17 (Total in Forum: 17) (Refresh)FirstPrevNext
QuestionDefault File NamememberNamazi21:42 13 Nov '07  
AnswerRe: Default File Namemembercykophysh3922:13 13 Nov '07  
QuestionRe: Default File NamememberNamazi23:13 13 Nov '07  
AnswerRe: Default File Namemembercykophysh3923:47 13 Nov '07  
Generaluseful articlememberNamazi2:41 7 Nov '07  
GeneralRe: useful articlemembercykophysh393:03 7 Nov '07  
GeneralMore simplememberjcparama6:52 26 Jun '07  
GeneralRe: More simplemembercykophysh398:58 26 Jun '07  
Generalin VB.NET1.1 console appmemberbhavna81623:38 19 Mar '07  
GeneralRe: in VB.NET1.1 console appmembercykophysh3923:50 19 Mar '07  
GeneralRe: in VB.NET1.1 console appmemberbhavna8160:02 20 Mar '07  
GeneralRe: in VB.NET1.1 console appmemberbhavna8160:06 20 Mar '07  
GeneralRe: in VB.NET1.1 console appmembercykophysh390:28 20 Mar '07  
Generalanother simple examplememberReynaldo Ferrer11:09 7 Mar '07  
GeneralRe: another simple examplemembercykophysh3922:54 7 Mar '07  
GeneralAlternativememberJon Sagara11:28 20 Sep '06  
GeneralRe: Alternativemembercykophysh3912:53 20 Sep '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 12 Feb 2007
Editor:
Copyright 2006 by Three Nine Consulting
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project