1
votes

i want export excel with StreamWriter. But error: Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

Code 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)
            {
                .....
            }
        }

How to solve this issue? Thank advance ;)

1
Have you checked to see that the file generated is a valid file? My guess is either the file didn't get created or is a 0 byte file that's causing problems. Looks like you're writing from within ASP.NET so you need to make sure your ApplicationPool Identity can write in the Web folder. - Rick Strahl
Just a guess but could it be because of the response.clear() after setting the content type and header? - Damon

1 Answers

2
votes

Try this: In place of HttpContext.Current.Response.End() use HttpContext.Current.ApplicationInstance.CompleteRequest()