Click here to Skip to main content
15,909,091 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi ,

I should create a .txt file dynamically . After the text file is created, it should be downloaded by the user. For this purpose , I try the code (I simplified the code basically like below ):
C#
string blabla= "Hello World";
Response.Clear();
Response.ContentType = "text/plain";
Response.AddHeader("Exported text File", "attachment; filename=helloWorld.txt");
Response.ContentEncoding = Encoding.Default;
byte[] bytes = Encoding.Default.GetBytes(blabla);
Response.BinaryWrite(bytes);
Response.End();

But this code block behaves like Response.Write() . The content is written at the download page. There is no file to be downloaded.

Thanks for the replies in advance..
Posted
Updated 4-Sep-12 20:39pm
v2

1 solution

Try adding Content-Disposition in header.
Try this:
C#
string blabla = "Hello World";
Response.Clear();
Response.ContentType = "text/plain";
//Response.AddHeader("Exported text File", "attachment; filename=helloWorld.txt");
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=helloWorld.txt"));
Response.ContentEncoding = Encoding.Default;
byte[] bytes = Encoding.Default.GetBytes(blabla);
Response.BinaryWrite(bytes);
Response.End();




--Amit
 
Share this answer
 
v2
Comments
no_-_namee 5-Sep-12 3:08am    
Thanks for the reply :)
It works well, by the way what is the difference of "Content-Disposition" in header?
_Amy 5-Sep-12 3:16am    
It forces the browser to open save as dialogue with the attached file. Refer here[^].

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900