简体   繁体   中英

Download files error exception c#

I have a problem with my code .. if I download a file when the file is empty, I get an error

Unable to cast object of type 'System.DBNull' to type 'System.Byte[]'

My code C# is:

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 id=@id";

            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();
}

the Exception already explains what the problem is. Since the Data-Column from the Database is NULL (DbNull) you can not cast it to a byte[].

You have to check if sdr["Data"] != DBNull before you try to cast it. Such that you can avoid this exception.

if(sdr["Data"] != DBNull.Value)
   bytes = (byte[])sdr["Data"];

If you don't want that you can catch the exception using a try-catch block and do what has to be done when the Data is NULL.

Cheers Michael

Change

bytes = (byte[])sdr["Data"];

to something like:

const String DATA = "Data";
if (sdr.IsDBNull(sdr.GetOrdinal(DATA)))
{
   bytes = (byte[])sdr[DATA];
}
else
{
   //handle null
}

the exception is "unassigned local variable 'bytes'` Response.BinaryWrite(bytes); but I found a result .. the problem is the download button downloads the page instead .. I do not know if it's possible to disable the linkbutton if the value is null

                   try
                    {

bytes = (byte[])sdr["Data"];

                    }
                    catch (Exception ex )
                    {

                        ex.Equals(bytes = System.Text.Encoding.UTF8.GetBytes(String.Empty));

                    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM