1

I have a file in server .

I want download this file .

I use this code

try
    {
        Response.Clear();
        Response.ClearContent();
        Response.ClearHeaders();
        Response.BufferOutput = true;

        if (File.Exists(Server.MapPath("~/Upload/" + file)))
        {
            Response.AddHeader("Content-Disposition", "attachment; filename=" + file);
            Response.ContentType = "application/octet-stream";
            Response.WriteFile(("~/Upload/" + file));
            Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();
        }
        else
        {
            if (Request.UrlReferrer != null)
            {
                Type csType = GetType();
                string jsScript = "alert('File Not Found');";
                ScriptManager.RegisterClientScriptBlock(Page, csType, "popup", jsScript, true);
            }
        }
    }
    catch (Exception ex)
    {
        string errorMsg = ex.Message;
        ScriptManager.RegisterClientScriptBlock(Page, GetType(), "popup", errorMsg, true);
    }

But when i use this, I get error

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

in code

Response.End();

How to download all types of files?

Niloo
  • 1,205
  • 5
  • 29
  • 53

2 Answers2

0

Is this Web Forms, MVC, or a custom IHttpHandler?

In any event, you don't need to call Response.End() or HttpContext.Current.ApplicationInstance.CompleteRequest(), just return from your function and ensure nothing else is written to the response.

Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks a lot, This is a Web Forms. I remove `Response.End() HttpContext.Current.ApplicationInstance.CompleteRequest()`, I don't get error but don't download file . – Niloo Feb 07 '13 at 08:18
  • Are you able to debug your code? Can you step-through your code and see if any exceptions are thrown or caught? Consider removing your `try/catch` block. – Dai Feb 07 '13 at 08:23
  • Yes I debug it, but don't any exceptions are thrown or caught. – Niloo Feb 07 '13 at 08:28
0

Have you tried :

Response.TransmitFile(Server.MapPath("~/Upload/" + file));

instead of :

Response.WriteFile(("~/Upload/" + file));

You should also remove the BufferOutput (bad idea with Response.End() without Response.Flush())

jbl
  • 15,179
  • 3
  • 34
  • 101