错误无法评估表达式,因为代码已优化

时间:2016-04-22 08:44:13

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

我希望使用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)
            {
                .....
            }
        }

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

1 个答案:

答案 0 :(得分:2)

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