Response.Write/Response.BinaryWrite and File Download problem in UpdatePanel


(Solution to Sys.WebForms.PageRequestManagerParserErrorException)

You  may face problem when you write download file logic in aspx page code behind while the the control that fires the event to download file is in update panel. If you use Response.Write() or Response.BinaryWrite() method as shown below in async postback you will encounter Sys.WebForms.PageRequestManagerParserErrorException.
clip_image002
Page’s markup
1.<asp:scriptmanager id="ScriptManager1" runat="server">
2.asp:scriptmanager>
3.<asp:updatepanel id="UpdatePanel1" runat="server">
4.<contenttemplate>
5.<asp:button id=" ButtonDownload" runat="server"onclick="ButtonDownload_Click" text="Download"> >
6.asp:button>contenttemplate>
7.asp:updatepanel>


Page’s Code behind

01.protected void ButtonDownload_Click(object sender, EventArgs e)
02.{
03.string fileName = "song.wav";
04.string filePath = "Audio/song.wav";
05.Response.Clear();
06.Response.ContentType = "audio/mpeg3";
07.Response.AppendHeader("Content-Disposition","attachment; filename=" + fileName);
08.string fileSeverPath = Server.MapPath(filePath);
09.if (fileSeverPath != null)
10.{
11. 
12.byte[] fileBytes = GetFileBytes(fileSeverPath);
13. 
14.Response.BinaryWrite(fileBytes);
15. 
16.Response.Flush();
17.}
18.}
19.protected byte[] GetFileBytes(string url)
20.{
21.WebRequest webRequest = WebRequest.Create(url);
22.byte[] fileBytes = null;
23.byte[] buffer = new byte[4096];
24.WebResponse webResponse = webRequest.GetResponse();
25.try
26.{
27.Stream stream = webResponse.GetResponseStream();
28.MemoryStream memoryStream = new MemoryStream();
29.int chunkSize = 0;
30.do
31.{
32.chunkSize = stream.Read(buffer, 0, buffer.Length);
33.memoryStream.Write(buffer, 0, chunkSize);
34.while (chunkSize != 0);
35.fileBytes = memoryStream.ToArray();
36. 
37.}
38.catch (Exception ex)
39.{
40.Response.Write(ex.Message);
41.}
42. 
43.return fileBytes;
44.}

clip_image006
Here is it. Enjoy!

Popular Posts