C++/CLI Code Snippet - Convert file to byte array

C++/CLI Code Snippet - Convert file to byte array

C++/CLI Code Snippet - Convert file to byte array

C++/CLI code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting.

Bookmark:

C++/CLI Code Snippet - Convert file to byte array

This .Net C++/CLI code snippet convert external file to byte array. Converting file into byte array important to store binary file in database, send to other systems using remoting. To use this function simply provide file path to external file. This function uses System.IO name space to open file using FileStream and reading from BinaryReader. Modify the exception handling section to as your project requirements.

array<System::Byte> ^FileToByteArray(System::String ^_FileName)
{
    array<System::Byte> ^_Buffer = nullptr;

    try
    {
        // Open file for reading
        System::IO::FileStream ^_FileStream = gcnew System::IO::FileStream(_FileName, System::IO::FileMode::Open, System::IO::FileAccess::Read);

        // attach filestream to binary reader
        System::IO::BinaryReader ^_BinaryReader = gcnew System::IO::BinaryReader(_FileStream);

        // get total byte length of the file
        System::IO::FileInfo ^_FileInfo = gcnew System::IO::FileInfo(_FileName);
        System::Int64 _TotalBytes = _FileInfo->Length;

        // read entire file into buffer
        _Buffer = _BinaryReader->ReadBytes(safe_cast<Int32>(_TotalBytes));

        // close file reader
        _FileStream->Close();
        delete _FileStream;
        _BinaryReader->Close();
    }
    catch (Exception ^_Exception)
    {
        // Error
        Console::WriteLine("Exception caught in process: {0}", _Exception->ToString());
    }

    return _Buffer;
}


Here is a simple example showing how to use above function (FileToByteArray) load external image in a file to byte array and show it in a picturebox (this is just to demonstrate this function, there are other methods to load image in picturebox).

System::IO::MemoryStream ^_MemoryStream = gcnew System::IO::MemoryStream(FileToByteArray("C:\\sample-image.jpg"));
pictureBox1->Image = System::Drawing::Image::FromStream(_MemoryStream);


Here is a simple example showing how to use above function (FileToByteArray) to store image in sql server database. This example shows how to read external file and convert it into byte array and then insert binary data into SQL server as a new record using sql parameter.

// set temporary variable for database connection
System::Data::SqlClient::SqlConnection ^_SqlConnection = gcnew System::Data::SqlClient::SqlConnection();

// assign database connection string
_SqlConnection->ConnectionString = "Server=SERVERADDRESS;Database=DATABASENAME;Uid=USERID;Pwd=PASSWORD;";

// Connect to database
try
{
    // open database connection
    _SqlConnection->Open();

    // Set SQL statement to insert new record to database
    System::String ^_SQL = "INSERT INTO sampletable (name, price, image) VALUES ('sample product name', 22.75, @image)";

    // lets add this record to database
    System::Data::SqlClient::SqlCommand ^_SqlCommand = gcnew System::Data::SqlClient::SqlCommand(_SQL, _SqlConnection);

    // Add image as SQL parameter
    System::Data::SqlClient::SqlParameter ^_SqlParameter = gcnew System::Data::SqlClient::SqlParameter("@image", SqlDbType::Image);

    // convert image file to byte array and pass to sql parameter value
    _SqlParameter->Value = FileToByteArray("C:\\sample-image.jpg");
    _SqlCommand->Parameters->Add(_SqlParameter);

    // Executes a Transact-SQL statement against the connection 
    _SqlCommand->ExecuteNonQuery();

    // Dispose command
    delete _SqlCommand;
    _SqlCommand = nullptr;

}
catch (Exception ^_Exception)
{
    // Error
    Console::WriteLine("Exception caught in process: {0}", _Exception->ToString());
}

// close database connection
_SqlConnection->Close();


C++/CLI Keywords Used:

  • FileStream
  • BinaryReader
  • FileInfo
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, SQL, FileStream, BinaryReader, FileMode, File to byte array, Remoting, Store binary in database, SQL Server Binary Data
  • Programming Language : C++/CLI

External Resources:

Leave a comment