Getting a image (blob) from mysql using reader.GetBytes??

T

Tinus

Hello all,

I've been searching for an answer for a day now (Google) and can't find what
I'm doing wrong :-(
The problem is as follows. I'm trying to read a blob from a mysql table.
However I get the following error:
'Source array was not long enough. Check scrIndex and lenght, and the
array's lower bounds.'

Image photo = null;
while (reader.Read())
{
long len = reader.GetBytes(1, 0, null, 0, 0);
Byte[] buffer = new Byte[len];
reader.GetBytes(1, 0, buffer, 0, (int)len);
photo = Image.FromStream(new MemoryStream(buffer));
}

The image is correctly stored in the MySql table as a blob because I can get
the image back using a DataTable and display it in a pictureBox. But I want
to use the reader function.

Hopefully someone here can help me solve the problem which lies in the above
code!? The mentioned error is generated on the code: reader.GetBytes(1, 0,
buffer, 0, (int)len);

Thanks in advance!
Regards,
Tinus
 
I

Ignacio Machin \( .NET/ C# MVP \)

Hi,


I posted this code yesterday, it works with Sql provider but it should be
the same with any other.


cheers,

--
Ignacio Machin,
ignacio.machin AT dot.state.fl.us
Florida Department Of Transportation




protected override void Load()
{
saved = true;

//generate a new local name for this file
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "LoadDocument";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@dID", SqlDbType.Int).Value = id;
SqlDataReader reader = DataProvider.ExecuteReader( cmd);
while( reader.Read() )
{
this.comment = "";
this.origname = reader["OrigName"].ToString();
this.dDate = Convert.ToDateTime( reader["dDate"]);
//Now we have to save the image

this.name = Guid.NewGuid().ToString() + "." + origname.Substring(
origname.LastIndexOf(".")+1);
physicalname = physicalname + @"\" + name;
ExtracFileFromDB( reader);

}
reader.Close();
}
protected void ExtracFileFromDB( SqlDataReader reader)
{
FileStream file = new FileStream( physicalname, FileMode.Create);
file.Write( (byte[])reader["Data"], 0,
((byte[])reader["Data"]).GetUpperBound(0)+1 );
file.Close();
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top