I have a very particular scenario where user can download a file from server by clicking on a button on the web page. I am achieving this through Response object. This is working fine.
But now I want to close the web page once the download completes. I have already tried the below code.
protected void btnDownloadFM_Click(object sender, EventArgs e)
{
bool isSucced = DownloadFile();
if (isSucced)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
}
The above code is not working. But if I comment out the file download code it is working fine(the web page close properly).
protected void btnDownloadFM_Click(object sender, EventArgs e)
{
//bool isSucced = DownloadFM();
bool isSucced = true;
if (isSucced)
{
ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
}
}
Below is the code block for downloading the file.
private bool DownloadFM()
{
try
{
//Get the file byte array from DB.
byte[] bytes = GetFileBytesFromDB();
string fileName = "DownloadedFile.txt";
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
string contentDisposition;
if (Request.Browser.Browser == "IE")
contentDisposition = "attachment; filename=" + Uri.EscapeDataString(templateName);
else
{
contentDisposition = "attachment; filename*=UTF-8''" + Uri.EscapeDataString(templateName);
}
Response.AddHeader("Content-Disposition", contentDisposition);
Response.AddHeader("Content-Length", bytes.Length.ToString());
Response.AddHeader("X-Download-Options", "noopen");
Response.ContentType = "application/octet-stream";
Response.OutputStream.Write(bytes, 0, bytes.Length);
Response.Flush();
Response.Close();
return true;
}
catch (Exception ex)
{
//Log error message to DB
return false;
}
}
Am I doing anything wrong here?