我在网格视图中有下载链接,当我点击它时,会弹出一个保存对话框,下载Excel填充。
但是我收到错误“无法评估表达式,因为代码已经过优化,或者本机框架位于调用堆栈之上。”在Response.End()
。
代码:
protected void grdFiles_RowCommand(object sender, GridViewCommandEventArgs e)
{
try
{
if (e.CommandName == "download")
{
string _FileName = Convert.ToString(e.CommandArgument);
//Response.Clear();
//Response.AppendHeader("Content-Disposition", "attachment; filename=" + _FileName);
//Response.ContentType = "application//octet-stream";
//Response.TransmitFile(Server.MapPath("~/Files/" + _FileName));
//Response.End();
// Get the physical Path of the file(test.doc)
string filepath = Server.MapPath("test.doc");
// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(Server.MapPath("~/Files/" + _FileName));
// Checking if file exists
if (file.Exists)
{
// Clear the content of the response
Response.ClearContent();
// LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
// Add the file size into the response header
Response.AddHeader("Content-Length", file.Length.ToString());
// Set the ContentType
Response.ContentType = "application/vnd.ms-excel";
// Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
Response.TransmitFile(file.FullName);
// End the response
Response.End();
}
}
}
catch (Exception ex)
{
}
}
答案 0 :(得分:2)
此错误的另一个可能原因可能是因为您的网格位于更新面板中?
如果是这种情况,我建议您将网格控件添加为Post back触发器:
<asp:UpdatePanel runat="server" ID="UpdatePanel1">
<Triggers>
<asp:PostBackTrigger ControlID="grdFiles" />
</Triggers>
<ContentTemplate>
<gridview ID="grdFiles" runat="server">
your grid view content
</gridview>
</ContentTemplate>
</asp:UpdatePanel>
虽然将整个网格作为Post back触发器可能过度杀戮(可能会发生分页后退等),您可以尝试将下载链接创建为模板列,并将网格内的控件设置为回发触发器
我有一个类似的问题,我使用导出按钮作为下载按钮,并使用网格命令选择一个细节,只有当网格中的某些东西被选中后才能使这个按钮可用,然后在此处放置一个回发触发器按钮而不是在网格上。
答案 1 :(得分:0)
这是因为ThreadAbortException。尝试处理这个特定的例外。
try
{
if (file.Exists)
{
//do something
}
response.End();
}
catch (ThreadAbortException ex)
{
//Log trace info
}
答案 2 :(得分:0)
有一种方便的方法来处理&#34;无法评估表达式,因为代码已经过优化,或者本机框架位于调用堆栈之上。&#34;的问题。您需要在“输出”窗口中进行书写。
使用System.Diagnostics添加;
为错误的行添加Try / Catch
在Catch中添加这些行
try
{ ..}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
Debug.WriteLine(ex.StackTrace);
Debug.WriteLine(ex.InnerException.ToString());
}
只需调试并检查输出窗口
希望它有所帮助。
答案 3 :(得分:-1)
将文件路径存储在Web.Config文件中并尝试以下代码:
string filename = "test.doc";
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("Path") + "\\\\" + filename;
FileInfo file = new FileInfo(FilePath);
if (file.Exists)
{
Response.AppendHeader("content-disposition",
"attachment; filename=" + filename);
Response.ContentType = "application/download";
Response.WriteFile(FilePath);
Response.End();
}