Force download of a file on web server - ASP .NET C#
Create a separate HTTP Handler (DownloadSqlFile.ashx):
<%@ WebHandler Language="C#" Class="DownloadHandler" %>
using System;
using System.Web;
public class DownloadHandler : IHttpHandler {
public void ProcessRequest(HttpContext context) {
var fileName = "myfile.sql";
var r = context.Response;
r.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
r.ContentType = "text/plain";
r.WriteFile(context.Server.MapPath(fileName));
}
public bool IsReusable { get { return false; } }
}
Then make the button in your ASP.NET page navigate to DownloadSqlFile.ashx
.
You need to tell the browser that what you are sending is not html and shouldn't be displayed as such in the browser. The following code can be used to return some text in your server-side code and it will present the save dialog to the user as you wanted:
Response.Clear(); //eliminates issues where some response has already been sent
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.sql", filename));
Response.Write(yourSQL);
Response.End();
filename
: the name you wish to give it
yourSQL
: the content of the sql file
The problem is that you're using the code on the same page as is currently loaded in the browser. You are attempting to modify the response stream and disposition of the current loaded page. Instead, create a separate HttpHandler, as suggested by Mehrdad. Then on the click of the button, you will invoke the URL to the handler. The button could even be a simple hyperlink that had the following as the source URL:
<a href="DownloadSqlFile.ashx">Download SQL</a>
Make sense? The point being, you cannot modify the response of the already loaded page. Launch a new request using a handler to do the work.