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.