Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating and saving a text file from a c# ASP.NET app

Tags:

c#

asp.net

I want to be able to create a text file and let the user save this to their own PC. Currently i have to do this:

StreamWriter sw;
sw = File.CreateText("C:\\results.txt");

Which obv saves on the web server but how can I replace that string with a link to their own computer? I looked at SaveFileDialog but it seems to only work for Windows Forms and not ASP sites, any advice?

Thanks in advance

like image 527
samcooper11 Avatar asked Nov 22 '25 08:11

samcooper11


1 Answers

You need to tell the Users Browser to Download the file. You can use the following code:

Response.ClearContent();
Response.ClearHeaders();
Response.ContentType="text/plain";
Response.AppendHeader( "content-disposition", "attachment; filename=" + filename );
Response.AppendHeader( "content-length", fileContents.Length );
Response.BinaryWrite( fileContents );
Response.Flush();
Response.End();

Where fileContents is a byte[] of the files contents. and filename is the name of the file to suggest to the user.

like image 193
FallenAvatar Avatar answered Nov 23 '25 23:11

FallenAvatar