Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Download text as file in ASP.NET

Tags:

c#

.net

asp.net

I am trying to download some text output from the screen as a text file. Following is the code. It's working on some pages and not working at all on other pages. Can anyone please 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());
}
like image 636
Vijay Avatar asked Feb 07 '13 15:02

Vijay


2 Answers

As already mentioned by Joshua, you need to write the text to the output stream (Response). Also, don’t forget to invoke 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: added more details

Edit 2: I was reading other SO posts where users were recommending to put quotes around the filename:

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

Source: https://stackoverflow.com/a/12001019/558486

like image 189
Rui Jarimba Avatar answered Oct 19 '22 04:10

Rui Jarimba


If that's your actual code, you never write the text to the response stream, so the browser never receives any data.

At the very least, you should need

Response.Write(sb.ToString());

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

You're also setting Response.Buffer = true; as part of your method but never explicitly flush the response to send it to the browser. Try adding a Response.Flush() after your write statement.

like image 27
Joshua Avatar answered Oct 19 '22 04:10

Joshua