0

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!

1
  • This is a common issue that I've seen lots of times. Code is being run on a server and the server sent the response back to the client and then code is trying to read the headers in the request. Best way of debugging is to put break points in code where response is sent to client. The error message should not occur before you hit the break point. If you do get the exception than there is more than one place in the code that is returning the response. Once you hit the break point you can step through the code to find out why code is continuing to process the request from client. Commented Sep 2, 2024 at 18:39

1 Answer 1

0

I ended up moving everything to a separate page (.aspx) and that solved my download issue!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.