Download text as a file in ASP.NET

I am trying to download text output from the screen as a text file. Below is the code. It works on some pages and generally does not work on other pages. Can anyone suggest what's wrong here?

protected void Button18_Click(object sender, EventArgs e){ Response.Clear(); Response.Buffer = true; Response.ContentType = "text/plain"; Response.AppendHeader("content-disposition", "attachment;filename=output.txt"); StringBuilder sb = new StringBuilder(); string output = "Output"; sb.Append(output); sb.Append("\r\n"); Response.Write(sb.ToString()); } 
+7
source share
2 answers

As Joshua already mentioned, you need to write the text in the output stream (Response). Also, be sure to call Response.End () after that.

 protected void Button18_Click(object sender, EventArgs e) { StringBuilder sb = new StringBuilder(); string output = "Output"; sb.Append(output); sb.Append("\r\n"); string text = sb.ToString(); Response.Clear(); Response.ClearHeaders(); Response.AppendHeader("Content-Length", text.Length.ToString()); Response.ContentType = "text/plain"; Response.AppendHeader("Content-Disposition", "attachment;filename=\"output.txt\""); Response.Write(text); Response.End(); } 

Edit 1: more details added

Edit 2: I read other SO posts in which users recommend putting quotes around the file name:

 Response.AppendHeader("content-disposition", "attachment;filename=\"output.txt\""); 

Source: fooobar.com/questions/937088 / ...

+25
source

If this is your actual code, you never write text to the response stream, so the browser never receives any data.

At least you need

 Response.Write(sb.ToString()); 

to write your text data in response. In addition, as an added bonus, if you know the length in advance, you should provide it using the Content-Length header so that the browser can show the download progress.

You also set Response.Buffer = true; as part of your method, but never explicitly clear the answer to send it to the browser. Try adding Response.Flush() after your write statement.

+4
source

All Articles