Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 4733
  • Last Modified:

C# MySQL memorystream, blob, read

I need to read an image file from a blob column in MySql database into a byte array that can be used as an image source in a WinForm. I do not know the size of the blob.
The code:
{
...
int id = 1;
UInt32 FileSize;
            byte[] rawData;
            IDbCommand dbcmd = dbconn.CreateCommand();
            string sql =
                       "SELECT image_file " +
                       "FROM current_session " +
                       "WHERE id = " + Id;
            dbcmd.CommandText = sql;
            IDataReader reader = dbcmd.ExecuteReader();
             reader.Read();  ...
}
At this point the reader should have the data.
How do I get that data to the rawData array?
0
eugene-g
Asked:
eugene-g
1 Solution
 
apeterCommented:
Try Below. outByte will have your rawdata.

// Size of the BLOB buffer.
int bufferSize = 100;                  
// The BLOB byte[] buffer to be filled by GetBytes.
byte[] outByte = new byte[bufferSize];  
// The bytes returned from GetBytes.
long retval;                            
// The starting position in the BLOB output.
long startIndex = 0;

while (reader.Read())
{
  // Create a file to hold the output.
  stream = new FileStream(
    "logo" + pubID + ".bmp", FileMode.OpenOrCreate, FileAccess.Write);
  writer = new BinaryWriter(stream);

  // Reset the starting byte for the new BLOB.
  startIndex = 0;

  // Read bytes into outByte[] and retain the number of bytes returned.
  retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);

  // Continue while there are bytes beyond the size of the buffer.
  while (retval == bufferSize)
  {
    writer.Write(outByte);
    writer.Flush();

    // Reposition start index to end of last buffer and fill buffer.
    startIndex += bufferSize;
    retval = reader.GetBytes(1, startIndex, outByte, 0, bufferSize);
  }
0

Featured Post

Veeam Task Manager for Hyper-V

Task Manager for Hyper-V provides critical information that allows you to monitor Hyper-V performance by displaying real-time views of CPU and memory at the individual VM-level, so you can quickly identify which VMs are using host resources.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now