C# – ASP.NET programmatic file download

asp.netcdownload

So I have a page on which I dynamically generate a table and link buttons all inside a large UpdatePanel. Each link button when clicked will cause this method to be called. The goal is to have the link point to a file in my DB and when clicked allow the user to open/save as that file. This exact method works fine on another page of my site with generally the same setup but on this one I'm getting:

Microsoft JScript runtime error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to Response.Write(), response filters, HttpModules, or server trace is enabled.
Details: Error parsing near '%PDF-1.3
%
1 0 ob'.

public void downloadFile(int fileID)
    {
        using (SurveyDataContext context = new SurveyDataContext())
        {
            try
            {
                var file = context.tblFiles.Single(f => f.FileID == fileID);
                Response.Clear();
                Response.Buffer = true;
                Response.BufferOutput = true;
                Response.ContentType = file.MIMEtype;
                Response.AppendHeader("Content-Disposition", "attachment; filename=\"" + file.FileName.Trim() + "\"");
                Response.AddHeader("Extension", file.FileName.Substring(
                    file.FileName.LastIndexOf('.') + 1).ToLower());
                Response.BinaryWrite(file.FileData.ToArray());

                Response.Flush();
                Response.End();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.InnerException);
            }
        }
    }

What am I doing wrong? I'm not doing any Response.Writes or anything. This method is the only that touches Response. Is there some other way I should be doing this?

Best Answer

Do you have an UpdatePanel or something like it?

If that's your case then you can do this at page load:

ScriptManager _scriptManager = ScriptManager.GetCurrent(this.Page);
_scriptManager.RegisterPostBackControl(Button1);