空引用异常(从mysql下载BLOB文件)

时间:2015-01-16 13:27:27

标签: c# mysql asp.net

单击链接按钮时,我试图从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";
}

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

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的数据库中

1 个答案:

答案 0 :(得分:0)

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

  

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

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

克服这种情况的最快方法是将合并分配:

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