0

I'm using the below code to download file in asp.net

public void DownloadFile(String fileName, String msg)
{
    if (String.IsNullOrEmpty(fileName))
    {
        fileName = "Document.txt";
    }

    HttpContext.Current.Response.Clear();
    HttpContext.Current.Response.BufferOutput = true;
    HttpContext.Current.Response.ContentType = "application/octet-stream";
    HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
    using (MemoryStream ms = new MemoryStream())
    {
        using (StreamWriter sw = new StreamWriter(ms))
        {
            sw.Write(msg);
            sw.Flush();
            ms.Position = 0;
            using (Stream download = ms)
            {
                byte[] buffer = new Byte[ms.Length];
                if (HttpContext.Current.Response.IsClientConnected)
                {
                    int length = 0;
                    length = download.Read(buffer, 0, buffer.Length);
                    HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                }
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.End();
            }
        }
    }
}

I'm getting exception at "HttpContext.Current.Response.End();"
HttpContext.Current.Response.End(); Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

What i need to change in that code? where I'm doing wrong.

4

1 回答 1

0

请查看对您有帮助的链接

如果需要,使用 try-catch 语句捕获异常

 try 
    {
    }
    catch (System.Threading.ThreadAbortException ex)
    {
    }
    For Response.End : Invoke  HttpContext.Current.ApplicationInstance.CompleteRequest    method instead of Response.End to bypass the code execution to the Application_EndRequest event
    For Response.Redirect : Use an overload, Response.Redirect(String url, bool endResponse) that passes false for endResponse parameter to suppress the internal call to Response.End

// code that follows Response.Redirect is executed
Response.Redirect ("mynextpage.aspx", false);
For Server.Transfer : Use Server.Execute method to bypass abort. When Server.Execute is used, execution of code happens on the new page, post which the control returns to the initial page, just after where it was called

限制/结论:

这是设计的。此异常对 Web 应用程序性能有不良影响,这就是正确处理场景很重要的原因。

于 2013-11-12T12:00:45.227 回答