June 7, 2020
Hot Topics:

Managed C++: Read Image Data Using the ADO.NET DataReader

  • By Tom Archer
  • Send Email »
  • More Articles »

Generic Method to Read Image Data

As promised, here's a generic method that takes as its parameters a data reader object pointer, a result set column index, and the name of a file. The function reads the data into memory and writes the image data to disk using the passed file name:
bool GetPictureValue(SqlDataReader* reader, 
                     int columnIndex,
                     String* destination)
#pragma push_macro("new")
#undef new

  bool success = false;

    if (!reader->IsDBNull(columnIndex))
      // Allocate a byte array
      Byte image[] = 
        __gc new Byte[Convert::ToInt32((reader->GetBytes(columnIndex,
                                                        0, 0, 0, 

      // Read the binary data into the byte array
      reader->GetBytes(columnIndex, 0, image, 0, image->Length);

      // Open FileStream and write buffer to file.
      FileStream* stream = new FileStream(destination, 
      stream->Write(image, 0, image->Length);
      success = true;
  catch (Exception* e)
    // handle exception
  return success;
#pragma pop_macro("new")

Continuing with the Northwind Employees table example, you can now enumerate through every employee's photo data, writing the image data to disk with the following code:

SqlConnection* conn = 
  new SqlConnection(S"Server=localhost;"
                    S"Integrated Security=true");
SqlCommand* cmd = 
  new SqlCommand(S"SELECT EmployeeID, Photo FROM Employees", conn);


SqlDataReader* reader  = cmd->ExecuteReader();
while (reader->Read())
  String* fileName = String::Format(S"{0}.jpg", reader->Item[0]);
  GetPictureValue(reader, 1, fileName);

Note that the only columns read are the EmployeeID (as it's used to determine the file name) and the Photo column (containing the image data).

Looking Ahead

This article illustrated how the ADO.NET data reader class enables you to easily read image data from a database, and it presented a sample generic function for reading this data and writing it to a disk file. The next article will show how to write image data from a disk file to a database via the SqlParameter class.

About the Author

Tom Archer owns his own training company, Archer Consulting Group, which specializes in educating and mentoring .NET programmers and providing project management consulting. If you would like to find out how the Archer Consulting Group can help you reduce development costs, get your software to market faster, and increase product revenue, contact Tom through his Web site.

Page 2 of 2

This article was originally published on January 31, 2005

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date