Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP C# Send File to Client

Tags:

c#

asp.net

Trying to send a file to the browser for download but after fiddling with it for over an hour can't seem to get it to work correctly.

I'm using the following code

    string filePath = Server.MapPath("/exports/test.txt");
    string downloadedFileName = "test.txt";

    Response.ContentType = "text/plain";
    Response.AppendHeader("content-disposition", "attachment; filename=" + downloadedFileName);
    Response.TransmitFile(filePath);
    Response.End();

It downloads to the browser but the file is filled with HTML from the page instead of the contents of the file. If I write out the directory of server.MapPath the file is located in that directory.

I'm eventually going to use this to send a accdb or mdb database to the browser, I'm just using txt as it's easy to find a proof of concept example online. What would I need to change outside of the ContentType if anything. Also would should the ContentType be for a database?

Thanks for any help in advance!

like image 223
bmanhard Avatar asked Nov 04 '13 23:11

bmanhard


1 Answers

It's probably because there is already some output queued in the Response stream ready for transmit. You must first clear it before transmitting your file. If you're using ASP.NET web forms, this will break your page though as the postback behavior will no longer work.

See related SO question and answer.

like image 109
Erik Noren Avatar answered Oct 06 '22 01:10

Erik Noren