7

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!

1
  • possible duplicate of Response.WriteFile Commented Nov 4, 2013 at 23:13

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

This is how it usually works for me:

Response.Clear();

if (Request.Browser != null && Request.Browser.Browser == "IE")
    sFileName = HttpUtility.UrlPathEncode(sFileName);

// Response.Cache.SetCacheability(HttpCacheability.Public); // that's upon you

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + sFileName + "\"");
                                                            // ^                   ^
// Response.AddHeader("Content-Length", new FileInfo(sFilePath).Length.ToString()); // upon you 
Response.WriteFile(sFilePath);

Response.Flush();
Response.End();

Comments

0

Try using .ashx generic handler to send file to browser bypassing most of the ASP.NET stack.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.