“无法将类型为'System.String'的对象强制转换为'System.Byte []'。” [英] "Unable to cast object of type 'System.String' to type 'System.Byte[]'."

查看:130
本文介绍了“无法将类型为'System.String'的对象强制转换为'System.Byte []'。”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  try
  {
    string query = "select F_Name,L_Name, Image from Employee where EID='" + txtid.Text + "'";
    if (con.State != ConnectionState.Open)
        con.Open();
    SqlCommand cmd = new SqlCommand(query, con);
    SqlDataReader sdr = cmd.ExecuteReader();
    sdr.Read();
    if(sdr.HasRows)
    {

        Ftxt.Text = sdr[0].ToString();
        Ltxt.Text = sdr[1].ToString();
     //   byte[] aa = (byte[])sdr[2];
        byte[] img = (byte[])(sdr[2]);
        if (img == null)
            pictureBox.Image = null;
        else
        {
            MemoryStream ms = new MemoryStream(img);
            pictureBox.Image = Image.FromStream(ms);

        }
        con.Close();
    }
    else
    {
        MessageBox.Show("ID Not Exist");
    }


}
catch (Exception )
{
    con.Close();
    throw;
}

推荐答案

首先,不要连接字符串来构建SQL命令。它让您对意外或故意的SQL注入攻击持开放态度,这可能会破坏您的整个数据库。使用参数化查询 - 或者任何人都可以通过键入文本框来销毁您的数据库...



如果SQLImage列的数据类型是NVARCHAR或类似的,然后它返回一个字符串 - 这不是一个字节数组,并且不能转换成一个字符串。



并且你的列中的数据很可能是也是错误的,因为你在插入它时几乎肯定会连接字符串 - 当你正确读出你的图像数据时,这会给你带来更多的问题。看看这个:为什么我会得到参数无效。我从数据库中读取图像时出现异常? [ ^ ] - 它显示了如何正确插入和检索图像。
First off, do not concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Use Parametrized queries instead - or anyone can destroy your database just by typing in a textbox...

If the datatype of the SQL "Image" column is NVARCHAR or similar, then it returns a string - which is not a byte array, and can't be cast to one.

And the chances are that the data in your column is wrong as well, since you have almost certainly concatenated strings when you inserted it - that will give you even more problems when you do read your image data out correctly. Look at this: Why do I get a "Parameter is not valid." exception when I read an image from my database?[^] - it shows you how to insert and retrieve images correctly.


这篇关于“无法将类型为'System.String'的对象强制转换为'System.Byte []'。”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆