I have a GridView which dispalys the file stored in the Database and a "DownloadFile" button to download it. I am using the following code to download but nothing happens. Earlier I was using Response.End in place of HttpContext.Current.ApplicationInstance.CompleteRequest(); and it was giving me an error. Now the error is gone and when I debug the code it goes through each line without any errors but still doesn't download the file. Please help!
if(e.CommandName == "DownloadFile")
{
int index = Convert.ToInt32(e.CommandArgument);
string PO_id = gvMyPending.DataKeys[index]["PO_id"].ToString();
String strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["PurchaseInventory"].ConnectionString;
using (SqlConnection con = new SqlConnection(strConnString))
{
using (SqlCommand cmd = new SqlCommand())
{
try
{
cmd.CommandText = "SELECT FileName, ContentType, Attachment FROM dbo.Orders where PO_id=@PO_id";
cmd.Parameters.AddWithValue("@PO_id", PO_id);
cmd.Connection = con;
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
Response.ContentType = dr["ContentType"].ToString();
Response.AddHeader("Content-Disposition", "attachment;filename=\"" + dr["FileName"]);
Response.BinaryWrite((byte[])dr["Attachment"]);
HttpContext.Current.ApplicationInstance.CompleteRequest();
}
}
catch(Exception Ex)
{
throw new ApplicationException(Ex.Message);
}
}
}