Retrieve previously stored byte array c# in the same format

I'm developing a winform C# application with SQLCe database.

When I'm uploading the image (and displaying it to PictureBox)

OpenFileDialog open = new OpenFileDialog();
open.Filter = "Image Files(*.jpg; *.jpeg; *.bmp)|*.jpg; *.jpeg; *.bmp";
if (open.ShowDialog() == DialogResult.OK)
{
    imageArray = System.IO.File.ReadAllBytes(@"" + open.FileName);
    using (MemoryStream ms = new MemoryStream(imageArray))
    {
        ms.Write(imageArray, 0, imageArray.Length);
        ms.Seek(0, SeekOrigin.Begin);
        companyLogoPB.Image = Image.FromStream(ms);
    }
}

It works perfectly - the byte array is converted to image and displayed on the PictureBox.

This is how I update it into the database (works perfectly):

string query = "UPDATE Company SET Logo=@Logo;";
SqlCeCommand cmd = new SqlCeCommand(query, con);
cmd.Parameters.AddWithValue("Logo", SqlDbType.Image).Value = imageArray;
int affectedRow = cmd.ExecuteNonQuery();

However, when I'm retrieving this data from the database:

private void getImageBytes()
{
    DataTable dt = new DataTable();
    string query = "SELECT LOGO FROM ECompany;";
    SqlCeDataAdapter da = new SqlCeDataAdapter(query, con);
    da.Fill(dt);
    return Encoding.ASCII.GetBytes(dt.Rows[0][0].ToString());
}
//snippet where error occurs:
using (MemoryStream ms = new MemoryStream(imageArray))
{
    ms.Write(imageArray, 0, imageArray.Length);
    ms.Seek(0, SeekOrigin.Begin);
    companyLogoPB.Image = Image.FromStream(ms); //ERROR
}

I got an error: Parameter is not valid. My guess is that the bytes returned is not encoded in the same format. Any idea how should I retrieve the stored image byte[] (which worked)?

Jon Skeet
people
quotationmark

This is the problem:

return Encoding.ASCII.GetBytes(dt.Rows[0][0].ToString());

You're converting the value to a string. It's not text data - just don't do it!

I would expect you to be able to just cast the value to byte[]:

return (byte[]) dt.Rows[0][0];

Also note that when you're loading the image, you'd be better off with:

companyLogoPB.Image = Image.FromStream(new MemoryStream(byteArray));

This is simpler code (you don't need to write the byte array then seek) and it's more likely to work, too - when you use Image.FromStream, that takes over ownership of the stream, so you shouldn't dispose of it yourself.

people

See more on this question at Stackoverflow