views:

23

answers:

1

I am saving a image into database with byte[] property like this:

ProfileModel:

private byte[] _imageData;

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

When I am trying to read image i have problem with converting of byte. I dont know how to convert reader into byte[]. I thought that its enough to convert.ToByte, but it doesnt works.

ThreadModel:

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

Its my method where I am reading image information:

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  A: 
byte[] buffer = new byte[reader.GetBytes(reader.GetOrdinal("ImageData"), 0, null, 0, int.MaxValue)];
reader.GetBytes(reader.GetOrdinal("ImageData"), 0, buffer, 0, int.MaxValue);

Might work, untested though.

Albin Sunnanbo
I need just do this at the and, or?ImageData = reader.GetBytes(reader.GetOrdinal("ImageData"), 0, buffer, 0, int.MaxValue);
Ragims
Nope, you should add "ImageData = buffer;", reader.GetBytes(...) returns the number of bytes written into "buffer".
Albin Sunnanbo
yep, but my ImageData is from type byte adn buffer is again from byte[]. then it is still the same problem like before.
Ragims
I did my ImageData also with byte[]. it rocks.thanks a lot!!
Ragims
Yes, that needs to be an array to, if you try to store a whole image in a single byte, that would be a very small image.
Albin Sunnanbo
hehe, you know i am very fresh in programming, and sometimes iam making stupid mistakes:)
Ragims