im试图在图片框中显示数据库附件中的图像,但在上出现错误
ImageByte = (byte[]) vcom.ExecuteScalar();
说
无法将类型为'System.String'的对象转换为类型为'System.Byte []'。
这是我的代码
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();
在MSAccess
中,附件二进制数据位于附件字段的子元素中。
这将返回byte[]
。该字节[]由MSAccess
填充,前20个字节包含MetaData
。
您可以使用Linq .Skip()
除去前20个字节
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;
...
这项工作吗?