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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With