1

我在服务器中有一个文件。

我想下载这个文件。

我使用此代码

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);
    }

但是当我使用它时,我得到了错误

无法计算表达式,因为代码已优化或本机框架位于调用堆栈顶部。

在代码中

响应。结束();

如何下载所有类型的文件?

4

2 回答 2

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.

于 2013-02-07T08:15:13.673 回答
0

你有没有尝试过 :

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

代替 :

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

您还应该删除 BufferOutput (不带的坏Response.End()主意Response.Flush()

于 2013-02-07T08:29:59.997 回答