Download text as file in ASP.NET

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


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.

Tags:

C#

.Net

Asp.Net