Sie sind auf Seite 1von 8

1 of 8

Sign up for our free weekly Web Dev Newsletter. ×

home articles quick answers discussions features community help Search for articles, questions, tips

Articles » Web Development » ASP.NET » Howto


 

Create and download a text file from a web page


Three Nine Consulting, 12 Feb 2007

   3.06 (16 votes) Rate this:

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.

Hide   Copy Code

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:

Hide   Copy Code

".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#
Hide   Copy Code
2 of 8

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
Hide   Copy Code

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
Downloading and uploading files
Send an attachment to the browser

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

Share
3 of 8

TWITTER

About the Author


Three Nine Consulting
Web Developer Three Nine Consulting
United Kingdom

Gary Woodfine is a freelance software developer based in Swindon, Wiltshire, UK. Experienced in
Financial Services, Security and Utilities covering all areas of software development including
Solution Architecture, software design and product development. Expertise in full stack software
development.

You may also be interested in...


A Solution Blueprint for DevOps Subnetting with IPv6 - Part 2/2

Secure File Download Page CrossCutterN: A Light Weight AOP


Tool for .NET

Multi-threaded file download Create Simple ASP.NET Progress


manager Bar Control

Comments and Discussions


 

You must Sign In to use this message board.

Search Comments

Spacing Relaxed   Layout Open All   Per page 25     Update

First Prev Next

Good function! Alan Oliveira 23-Jun-15 8:52 

It's a good function, but it doesn't work with update panel.

I'm writting only to alert who will try this with update panel.
4 of 8

And a way that works to me, was create another webform without updatePanel, and call this other page to execute the download
function.

Sign In · View Thread  

How to apply Styles to word file in asp.net Member 11432166 16-Jun-15 2:04 

Hi,

Can anyone tell me how to apply styles to the word document in asp.net using C#(create and download is working finely.)

Sign In · View Thread  

How to apply Styles to word file from web page Member 11432166 16-Jun-15 2:03 

Hi,

Can anyone tell me how to apply styles to the word document in asp.net using C#(create and download is working finely.)

Sign In · View Thread  

Thanks! xiaoyintao 27-Oct-14 17:47 

This article is helpful for me.Thanks a lot!

Sign In · View Thread  

Thanks! Manoj Nathwani 19-Feb-13 12:40 

Thanks for this!, its great

Sign In · View Thread  

wonderful! Janilane 22-Aug-12 1:37 

5 stars from me!

Sign In · View Thread  

‫اﻳﺠﺎد ﻓﺎﻳﻞ‬ soleymani_arak 2-Nov-11 21:29 

‫دﻣﺖ ﮔﺮم‬
‫ﺧﻴﻠﻲ ﺣﺎل دادي‬

Sign In · View Thread  

My vote of 5 Tory Netherton 29-Jun-11 12:06 

This article really helped me. I just wanted to write a string out to the client as an attached file. This taught me everything I
needed to do it.

Sign In · View Thread  

Re: My vote of 5 Three Nine Consulting 20-Mar-13 2:39 

Wow thanks! I had actually forgotten about this article!


I'm glad it helped you and thank you for the vote!
Apologies for taking so long to reply!

Kind Regards,
Gary
5 of 8

My Website || My Blog || My Articles

Sign In · View Thread  

My vote of 5 Member 7682030 17-Feb-11 4:20 

This article really helped me!!!

Sign In · View Thread  

dowload word file using vb.net trimandir prajapati 16-Sep-09 2:29 

hi.. i have save the word file using vb.net let say filename is "my examply [my file].doc" ..
then i download the file using vb.net..
the file is downloaded

but the problem is that when i download the file the in the filename the underscore (_) is appended whenever there is space like

"my_example_[my_file].doc"

what may be the reason of this

could anyone help me please


thanks in advance

trimp

Sign In · View Thread  

Default File Name Namazi 13-Nov-07 21:42 

Hi When the open dialog box shows up, there is a default file name in the TextBox,
I want to change it in my code,
how can I do this?

thank you.

Sign In · View Thread  

Re: Default File Name Three Nine Consulting 13-Nov-07 22:13 

Change the file extension of the file you are downloading

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

Re: Default File Name Namazi 13-Nov-07 23:13 

I don't know if I could describe my problem well.

as more details:

When a client downloads the files, the files all will be saved with name of the page!
6 of 8

(for example: file on server is named: a.doc and my page is named xyz.aspx, the file is saved on client as xyz.doc)
I want files to be saved with their own names.

thanks

Sign In · View Thread  

Re: Default File Name Three Nine Consulting 13-Nov-07 23:47 

what are you supplying as the file name you are downloading

Hide   Copy Code


Response.AddHeader("Content-disposition", "attachment; filename=" + Put Name Of File Here and
the Extensiion type );<br />
Response.ContentType = "application/octet-stream";<br />
Response.BinaryWrite(btFile);<br />
Response.End();

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

useful article Namazi 7-Nov-07 2:41 

Hi,
thank you so much.
As an example, to download a doc file to client I wrote this:
Hide   Copy Code
<br />
<br />
Response.AddHeader("Content-disposition", @"attachment; filename=~\XYZ.doc");<br />
Response.AddHeader("content-type", "application/msword");<br />
Response.WriteFile(@"~\XYZ.doc", false);<br />
Response.End();<br />

Sign In · View Thread  

Re: useful article Three Nine Consulting 7-Nov-07 3:03 

Cool,
Thanks.

I will try update the article at some point to show the simplified methods

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

More simple jcparama 26-Jun-07 6:52 


7 of 8

You can simplify this example because you don't need write de Textbox to a file first:

string sGenName = "Friendly.txt";


Response.AddHeader("Content-disposition", "attachment; filename=" + sGenName);
Response.ContentType = "application/octet-stream";
Response.Write(txtText.Text);
Response.End();

Greetings.

Juan Carlos Paramá

Sign In · View Thread  

Re: More simple Three Nine Consulting 26-Jun-07 8:58 

Sure you are correct, but if you read the article I actually say you don't need to do that, but I left that code in to illustrate
how to actually create a text file.

Thanks for your feedback though

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

in VB.NET1.1 console app salon 19-Mar-07 23:38 

How can i do the same in VB.NET 1.1 console application i.e. how can i set the MIME type for every extension and render it to an
HTML page?

Sign In · View Thread  

Re: in VB.NET1.1 console app Three Nine Consulting 19-Mar-07 23:50 

you would need to import the System.Web Namepspace into the Console App.

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

Re: in VB.NET1.1 console app salon 20-Mar-07 0:02 

C:\...\Module1.vb(580): Name 'Response' is not declared.

this is the error here

With Response
.AddHeader("Content-disposition", "attachment;filename=" & oAtmt.FileName)
.ContentType = "application/octet-stream"
.BinaryWrite(btFile)
.End()
8 of 8

End With

Sign In · View Thread  

Re: in VB.NET1.1 console app salon 20-Mar-07 0:06 

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?

Sign In · View Thread  

Re: in VB.NET1.1 console app Three Nine Consulting 20-Mar-07 0:28 

Check out this article for some info


http://dotnet.sys-con.com/read/45127.htm

Kind Regards,
Gary

My Website || My Blog || My Articles

Sign In · View Thread  

another simple example Jarvis 758 444f 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 !!!"))
.End()
End With

Reynaldo Ferrer

Sign In · View Thread  

Last Visit: 7-Dec-18 8:55     Last Update: 7-Dec-18 8:55 Refresh 1 2 Next »

General    News    Suggestion    Question    Bug    Answer    Joke    Praise    Rant    Admin   

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile Layout: Article Copyright 2006 by Three Nine Consulting
Select Language ▼
Web04 | 2.8.181205.1 | Last Updated 12 Feb 2007 fixed | Everything else Copyright © CodeProject, 1999-2018
fluid

Das könnte Ihnen auch gefallen