3
public void Downloadfile(string sFileName, string sFilePath)
{
    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.ClearContent();
    HttpContext.Current.Response.ClearHeaders();
    HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
    String Header = "Attachment; Filename=" + sFileName;
    HttpContext.Current.Response.AppendHeader("Content-Disposition", Header);
    HttpContext.Current.Response.AppendHeader("Cache-Control", "no-cache");
    System.IO.FileInfo Dfile = new System.IO.FileInfo(HttpContext.Current.Server.MapPath(sFilePath));
    HttpContext.Current.Response.TransmitFile(Dfile.FullName);
    HttpContext.Current.ApplicationInstance.CompleteRequest();
}

I have a download button, the click will return the call and download the corresponding file download, but sometimes file returns is detailt.aspx file. I do not understand what is happening. I need help. Thanks a lot

0

1 Answer 1

7

This has worked for me with out issue for a while now.

public void Downloadfile(string sFileName, string sFilePath)
{
    var file = new System.IO.FileInfo(sFilePath);

    Response.Clear();
    Response.AddHeader("Content-Disposition", "attachment; filename=" + sFileName);
    Response.AddHeader("Content-Length", file.Length.ToString(CultureInfo.InvariantCulture));
    Response.ContentType = "application/octet-stream";
    Response.WriteFile(file.FullName);
    Response.End();
}
3
  • 1
    Thanks David Negron reply. But when i using Response.End(), thorw exception: exception = {Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.} I dont understand bug. Can you explain. Sep 30, 2013 at 6:03
  • By any chance are you attempting to execute any additional code after the Downloadfile is called. The reason I ask is because I typically call this type of code from within an HttpHandler. For an example of this take a look at this article geekswithblogs.net/hmloo/archive/2012/03/07/… Sep 30, 2013 at 9:29
  • i just had the same issue here, after putting the response.clear and in general all the response commands after anything else you do (like memory stream reads) like the answer here solves the problem, otherwise you will not get any exception echoes, my case was permission issue to the filesystem because iis was running on different user than my visual studio and the exception was consumed, web page was giving an html output (probably the active page html, i didn't bother to read it) Feb 28, 2022 at 14:27

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.