Search code examples
c#oledb

How to Display attachments image from access db in picturebox


im trying to display image from database Attachments in picturebox but im getting error on

ImageByte = (byte[]) vcom.ExecuteScalar();

it say

Unable to cast object of type 'System.String' to type 'System.Byte[]'.

here is my code

byte[] ImageByte = null;
MemoryStream MemStream = null;

OleDbConnection cn = new OleDbConnection();
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/ALL/Database7.accdb";
cn.Open();

OleDbCommand command = new OleDbCommand();
command.Connection = cn;
string sql = "select Attachments from Contacts where ID = 1";
OleDbCommand vcom = new OleDbCommand(sql, cn);

ImageByte = (byte[]) vcom.ExecuteScalar();

MemStream = new MemoryStream(ImageByte);
pictureBox1.Image = Image.FromStream(MemStream);
cn.Close();

Solution

  • In MSAccess, attachments binary data are located in a sub element of the Attachment field.

    This will return a byte[]. This byte[] is padded by MSAccess, first 20 bytes are contains MetaData.

    You can use Linq .Skip() to get rid of those first 20 bytes

    string sql = "select Attachments.FileData from Contacts where ID = 1";
    OleDbCommand vcom = new OleDbCommand(sql, cn);
    
    byte[] ImageByte = (byte[]) vcom.ExecuteScalar(); //contains 20 extra bytes
    
    MemoryStream MemStream = new MemoryStream(ImageByte.Skip(20).ToArray()); //Read bytes starting at position 20
    
    Image image = Image.FromStream(MemStream); //Will work now
    pictureBox1.Image = image;
    ...
    

    Does this work?