8

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());
}
Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
Vijay
  • 385
  • 1
  • 4
  • 15
  • 4
    Could you solve someones problem if he would tell you that _"it's working on some pages and not working at all on other pages"_ without telling you what's not working? – Tim Schmelter Feb 07 '13 at 15:57

2 Answers2

31

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

Rui Jarimba
  • 11,166
  • 11
  • 56
  • 86
4

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.

Joshua
  • 8,112
  • 3
  • 35
  • 40
  • Sorry, forgot to include that line in the code above. It's still not working. Thanks. – Vijay Feb 07 '13 at 16:03
  • @Vj87 See my update, you're buffering so it might not be sending the content to the browser when you expect. Also, if this is a large amount of text, the entire file won't get sent to the browser until the server has buffered everything. You can also try setting `Response.Buffer` to false. – Joshua Feb 07 '13 at 16:09