Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force download of a file on web server - ASP .NET C#

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?

like image 625
Sameet Avatar asked May 16 '09 20:05

Sameet


2 Answers

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.

like image 61
mmx Avatar answered Sep 27 '22 20:09

mmx


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

like image 44
Neil Trodden Avatar answered Sep 27 '22 22:09

Neil Trodden