Search code examples
c#sqldatareadervarbinaryvarbinarymax

SqlDataReader: Read varbinary into byte array


I have a SQL Server table with a varbinary(max) column. I use it to store images in it. The images are selected with an OpenFileDialog, translated into a byte[] like this

public byte[] ConvertImageToByteArray(String filepath)
{
    try
    {
        return File.ReadAllBytes(filepath);
    }
    catch (Exception) 
    {
        throw; 
    }
}

and then stored into the database using this line of code:

sqlCmd.Parameters.Add("@image", SqlDbType.VarBinary).Value = image;

It looks like this stored in the database, so I guess all seems to work like expected.

enter image description here

Unfortunately I am unable to load the images back from the datatable.

I am using a SqlDataReader to do so:

DbSql db = new DbSql();

SqlDataReader dr = db.GetDataReader(sqlCmd);

if (dr.Read())
{
    if (!dr.IsDBNull(1))
        productName = dr.GetString(1);

    if (!dr.IsDBNull(2))
        identNumber = dr.GetString(2);

    [...]

    if (!dr.IsDBNull(23))
        comment = dr.GetString(23);

    if (!dr.IsDBNull(24))
    {
        byte[] image = dr.GetSqlBytes(24).Value;  // <- This is where I try to grab the image
    }
}

It seems like I am not able to create a proper byte[] with

image = dr.GetSqlBytes(24).Value;

because my next step is not able to turn it into an image again:

public Image ConvertImageFromByteArray(byte[] array)
{
        try
        {
            MemoryStream ms = new MemoryStream(array);
            return Image.FromStream(ms);
        }
        catch (Exception) { throw; }
    }

EDIT: When trying something like pictureBox.Image = ConvertImageFromByteArray(image) I get an error saying "Invalid parameter" (self translated, saying "Ungültiger Parameter" in german) enter image description here

Anyone able to offer a solution?


Solution

  • Once you cast your varbinary(MAX) to a byte array

    image = (byte[])dr[24];
    

    Try this..

        MemoryStream ms = new MemoryStream(image);
        imagePictureBox.Image = System.Drawing.Image.FromStream(ms);
    

    This is how I create the byte array...

        if (File.Exists(sLogoName) == false)
           throw new Exception("File Not Found: " + sLogoName);
        FileStream sourceStream = new FileStream(sLogoName, FileMode.Open, FileAccess.Read);
        int streamLength = (int)sourceStream.Length;
        Byte[] byLogo = new Byte[streamLength];
        sourceStream.Read(byLogo, 0, streamLength);
        sourceStream.Close();