I'm trying to allow a user to download a file using the following server-side C# code:
public static HttpResponse ExportDataToUser(string settings)
{
string filename = "CurrentSettings.txt";
System.IO.StringWriter sw = new System.IO.StringWriter(new StringBuilder(settings));
//Open a memory stream that you can use to write back to the response
byte[] byteArray = Encoding.ASCII.GetBytes(sw.ToString());
MemoryStream s = new MemoryStream(byteArray);
StreamReader sr = new StreamReader(s, Encoding.ASCII);
//Write the stream back to the response
HttpContext.Current.Response.BufferOutput = true;
HttpContext.Current.Response.Write(sr.ReadToEnd());
HttpContext.Current.Response.ContentType = "text/plain";
HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + filename);
HttpContext.Current.Response.Flush();
//sr.Close();
//sr.Dispose();
HttpContext.Current.Response.Close();
return HttpContext.Current.Response;
}
When the method reaches the Flush
line, this download bar at the bottom of the screen appears but when I click Open
, the I am prompted that the "file couldn't be downloaded." The client side call that invokes this method has dataType: "text/plain"
. Does anyone have an idea why the download is failing?