title: How to close a web page from code behind after succesful download of a file through Response object in c#?
body: <p>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.</p>
  
  <p>But now I want to close the web page once the download completes. I have already tried the below code.</p>
  
  <pre><code>protected void btnDownloadFM_Click(object sender, EventArgs e)
  {
          bool isSucced = DownloadFile();
  
          if (isSucced)
          {
              ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
          }
  }
  </code></pre>
  
  <p>The above code is not working. But if I comment out the file download code it is working fine(the web page close properly).</p>
  
  <pre><code>protected void btnDownloadFM_Click(object sender, EventArgs e)
  {
              //bool isSucced = DownloadFM();
              bool isSucced = true;
  
              if (isSucced)
              {
                  ClientScript.RegisterStartupScript(typeof(Page), "closePage", "window.close();", true);
              }
  }
  </code></pre>
  
  <p>Below is the code block for downloading the file.</p>
  
  <pre><code>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;
      }
  }
  </code></pre>
  
  <p>Am I doing anything wrong here?</p>