I need to force the initiation of download of a .sql file, when user clicks a button in my ASP .NET (C#) based web application.
As in, when the button is clicked, a save as dialog should open at the client end...
How do I do this?
EDIT
This is the code I am using
string sql = "";
using (System.IO.StreamReader rdr = System.IO.File.OpenText(fileName))
{
sql = rdr.ReadToEnd();
}
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=Backup.sql");
Response.Write(sql);
Response.End();
This is the error that I'm getting...
alt text http://img40.imageshack.us/img40/2103/erroro.gif
What's wrong?
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:
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.
Add a
Response.Clear
before youResponse.Write
to fix the error, if stated properly in the Chrome dialog.So to integrate in the snippet in other answer...
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:
filename
: the name you wish to give ityourSQL
: the content of the sql fileThe solution below works for me
Create a separate HTTP Handler (DownloadSqlFile.ashx):
Then make the button in your ASP.NET page navigate to
DownloadSqlFile.ashx
.