I am using the code below to download an Excel file. Once the Response.End() call runs, I want to close window. However, this isn’t happening. Please see the code I have so far below.
'Write it back to the client
Dim filename As String = "FullExtract_" & Now.Year.ToString & Now.Month.ToString & Now.Day.ToString & ".xlsx"
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.AddHeader("content-disposition", "attachment; filename=" & filename)
Response.BinaryWrite(pck.GetAsByteArray())
Response.End()
'cursor not reaching to below code
Page.ClientScript.RegisterStartupScript(Me.GetType(), "closedownload", "JavaScript:window.close(); return false;")
How do I close the window?
Don’t call Response.End. That throws a ThreadAbortException, which will cause all kinds of nasty things. Also, this exception is what is preventing your Page.ClientScript after the Response.End not to fire. So just remove the Response.End. Its no longer needed and a hold over from the old classic ASP days.
EDIT: You can’t close the window like that; when you send the file for download, it should open a file save prompt on the users OS, and the file will download. The html RegisterStartupScript would generate would end up as part of the file download I’d think. You should probably have the page which the button or link that triggers the download open a new window using target=”_blank” or via javascript, that window would close automatically or not even opene depending on the browser.