如何Convert.ToByte [] sql reader?

时间:2010-08-26 07:45:45

标签: sql asp.net-mvc byte

我将图像保存到具有byte[]属性的数据库中,如下所示:

ProfileModel:

private byte[] _imageData;

public byte[] ImageData
{
    get
    {
        return _imageData;
    }
    set
    {
        _imageData = value;
    }
}

当我尝试读取图像时,我有转换字节的问题。我不知道如何将读者转换为byte[]。我认为它足以转换.ToByte,但它不起作用。

线程模型:

private byte _imageData;
public byte ImageData
{
    get
    {
        return _imageData;
    }
    set
    {
        _imageData = value;
    }
}

我正在阅读图像信息的方法:

cmd = new SqlCommand();
cmd.Connection = connection;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = @"SELECT ImageData, " 
                 + " ContentType, " 
                 + " ImageName " 
                 + " FROM UsersImage "
                 + " WHERE UserName = @UserName ";

cmd.Parameters.AddWithValue("@UserName", ThreadUserName);

reader = cmd.ExecuteReader();
if (reader.Read())
{
    if (reader["ContentType"] != DBNull.Value)
    {
        ContentType = Convert.ToString(reader["ContentType"]);
    }

    if (reader["ImageName"] != DBNull.Value)
    {
        ImageName = Convert.ToString(reader["ImageName"]);
    }

    if (reader["ImageData"] != DBNull.Value)
    {
        ImageData = Convert.ToByte(reader["ImageData"]);
    }

    int affectedRows = cmd.ExecuteNonQuery();
    if (affectedRows != 1)
    {

    }
}
reader.Close();

1 个答案:

答案 0 :(得分:1)

byte[] buffer = new byte[reader.GetBytes(reader.GetOrdinal("ImageData"), 0, null, 0, int.MaxValue)];
reader.GetBytes(reader.GetOrdinal("ImageData"), 0, buffer, 0, int.MaxValue);

可能会工作,但未经测试。