【问题标题】:Error Unable to evaluate expression because the code is optimized错误无法评估表达式,因为代码已优化
【发布时间】:2016-08-15 19:17:40
【问题描述】:

我想用 StreamWriter 导出 excel。 但错误:无法计算表达式,因为代码已优化或本机框架位于调用堆栈顶部。

代码 C#:

private void ExportToExcel()
        {
            string filePath = string.Empty;
            try
            {
                if (fn.CheckRowOnDataTable(dtExport))                        
                {
                    string path = Server.MapPath(@"~/EXCEL/");
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }

                    string fileName = string.Format("{0}_{1}.xls", this.PROGRAM_ID, DateTime.Now.ToString("yyyyMMdd_HHmmss"));
                    filePath = string.Format("{0}{1}", path, fileName);

                    if (File.Exists(filePath))
                    {
                        File.Delete(filePath);
                    }

                    using (StreamWriter writer = new StreamWriter(filePath))
                    {
                        writer.Write(GenerateExcel());
                    }

                    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("filename={0}", fileName));
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.WriteFile(filePath); <<< Line Error
                    HttpContext.Current.Response.End();
                }
                else
                {
                    .....                      
                }                   
            }
            catch (OverflowException e)
            {
                .....
            }
            catch (Exception ex)
            {
                .....
            }
        }

如何解决这个问题? 谢谢提前;)

【问题讨论】:

  • 您是否检查过生成的文件是否为有效文件?我的猜测是文件没有被创建或者是一个导致问题的 0 字节文件。看起来您是在 ASP.NET 中编写的,因此您需要确保您的 ApplicationPool Identity 可以写入 Web 文件夹。
  • 只是猜测,但可能是因为设置内容类型和标题后的response.clear()?

标签: c# asp.net excel error-handling runtime-error


【解决方案1】:

试试这个:代替HttpContext.Current.Response.End()使用HttpContext.Current.ApplicationInstance.CompleteRequest()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-14
    • 1970-01-01
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    相关资源
    最近更新 更多