This is my first time working in an ASP.NET application (and C# in general) and I have issues creating a file in memory and downloading it from the browser.
My component .ascx file contains a button. I decided to go with a component because this is used in multiple pages of the application.
<telerik:RadImageButton ID="exportExcel" runat="server" Width="16" Height="16"
CommandArgument="xlsx" AutoPostBack="True" OnClick="OnExport">
<Image Url="/images/fs/16x16/excel.gif" />
</telerik:RadImageButton>
And the method in the .cs file behind it:
protected void OnExport(object sender, EventArgs e)
{
try
{
MemoryStream memoryStream = new MemoryStream();
TextWriter writer = new StreamWriter(memoryStream);
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
writer.WriteLine("Line 3");
writer.Flush();
Response.Clear();
Response.ContentType = "application/force-download";
Response.AddHeader("Content-Disposition", "attachment; filename=file.txt");
Response.AddHeader("Content-Length", memoryStream.Length.ToString());
memoryStream.WriteTo(Response.OutputStream);
Response.Flush();
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
catch (Exception exception)
{
usp_ins_error_log errorLog = new usp_ins_error_log();
errorLog.runSP(exception, false);
}
}
Nothing seems to download (as the error is swalloed), but if I remove the try-catch block around it, I get an error:
Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException (0x80004005): Server cannot set content type after HTTP headers have been sent.
Could someone help me how to solve this? Thanks!