我试图在单击链接按钮时从mysql数据库下载blob文件。以下是我的代码:

Response.Buffer = true;
Response.Charset = "";
if (context.Request.QueryString["download"] == "1")
{
    context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename);
}

try
{
    Response.BinaryWrite(bytes);
}
catch (NullReferenceException ex) {
    LinkButton2.Text = "No file was uploaded";
}


但是它在“字节”上给出了空引用异常。字节在以下语句中初始化

if (!Convert.IsDBNull(r["proposalDoc"]))
{
    this.bytes = (byte[])r["proposalDoc"];
}


数据检索代码:

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {

            this.Time = String.Format("{0:HH:mm:ss}", DropDownList1.SelectedValue);
            String query = "Select * from event where time='" + this.Time + "'";
            MySqlConnection conn = new MySqlConnection(connection);

            MySqlCommand cmd = new MySqlCommand(query, conn);

            DateTime time = DateTime.Today;

            conn.Open();

            MySqlDataReader r = cmd.ExecuteReader();

            while (r.Read())
            {
                TextBox1.Text = r["name"].ToString();
                TextBox2.Text = r["Proposedby"].ToString();
                if (!Convert.IsDBNull(r["proposalDoc"]))
                {
                    this.bytes = (byte[])r["proposalDoc"];
                }

                TextBox5.Text = Calendar1.SelectedDate.ToString("d");
                TextBox6.Text = r["time"].ToString();
                TextBox7.Text = r["Society"].ToString();
                TextBox8.Text = r["venue"].ToString();

            }


而且,该记录存在于proposalDoc的数据库中

最佳答案

如果您打算获取proposalDoc的第一个非空值,请注意(per the MSDN):


  DBNull.Value用于指示缺少的值。它不是
  等效于null或String.Empty。因此,例如
  C#中的Convert.IsDBNull(null)或Visual中的Convert.IsDBNull(Nothing)
  基本返回false。


因此,如果r["proposalDoc"]null,则将为null分配this.bytes

解决此问题的最快方法是将任务合并为空:

this.bytes = this.bytes ?? (byte[])r["proposalDoc"];

关于c# - 空引用异常(从mysql下载BLOB文件),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27984998/

10-09 19:38