我有一個問題,我的代碼..如果我下載文件時,該文件是空的,我得到一個錯誤下載文件錯誤異常C#
無法轉換類型爲「System.DBNull」對象類型 'System.Byte []'
我的代碼C#是:
protected void DownloadFile(object sender, EventArgs e)
{
int id = int.Parse((sender as LinkButton).CommandArgument);
byte[] bytes;
string fileName, contentType;
// string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection("Data Source=OUSSAMA-PC;Initial Catalog=evamedica;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "select id,soins,date_sejour,civilite,nom,prenom,date_naissance,email,gsm,adresse,code_postal,ville,pays,accompagnant,nbr_accompagnant,commentaire,connu_evamedica,Name,ContentType,Data from devis where [email protected]";
cmd.Parameters.AddWithValue("@id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
sdr.Read();
bytes = (byte[])sdr["Data"];
contentType = sdr["ContentType"].ToString();
fileName = sdr["Name"].ToString();
}
con.Close();
}
}
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contentType;
Response.AppendHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
代碼片段用於JS/CSS/HTML。它不適用於C#。 – 2014-09-26 10:49:35
對不起兄弟,我是一個新成員 – 2014-09-26 20:56:40