title: ASHX File Download Corrupted File
body: <p>When ever I access my ashx eg download.ashx?id=18 it gets the file, but then when the save dialog pops up it wants me to save download.ashx rather than the file I have stored in the Database (lets say mypdf.pdf) If you open the file download it opens in Visual Studio and doesnt really show anything useful. What is causing this, I have tried it in many browsers and many machines and it all does the same?</p>
  
  <p>Thanks</p>
  
  <pre><code>        string id = ctx.Request.QueryString["id"];
          string name = null;
          string mime = null;
  
          SqlConnection con = new SqlConnection(CONN);
          SqlCommand cmd = new SqlCommand("DownloadActivityFile", con);
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddWithValue("@aid", id);
  
          byte[] afile = null;
          try
          {
              con.Open();
              SqlDataReader reader = cmd.ExecuteReader();
  
              while (reader.Read())
              {
                  mime = reader["ActivityFileMIME"].ToString();
                  ctx.Response.ContentType = mime;
                  afile = (byte[])reader["ActivityFile"];
                  name = reader["ActivityFileName"].ToString();
              }
              ctx.Response.Buffer = false;
              ctx.Response.ContentType = mime;
              ctx.Response.AddHeader("content-disposition", string.Format("attachment; {0}", name));
              ctx.Response.Clear();
              ctx.Response.BinaryWrite(afile);
              ctx.Response.End();
          }
          catch (Exception e)
          {
              ctx.Response.Write(e.ToString());
          }
          finally
          {
              con.Close();
          }
  </code></pre>