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

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

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

C++/CLI code snippet save byte array in to an external file. This function useful to store binary data in files. This function can be use when retrieving binary data from database and save it to an external file.

Bookmark:

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

This .Net C++/CLI code snippet save byte array in to an external file. This function useful to store binary data in files. Function return true if byte array successfully written to file, else return false. Most common method to store binary data in database is as a byte array format. This function can be use when retrieving binary data from database and save it to an 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.

bool ByteArrayToFile(System::String ^_FileName, array<System::Byte> ^_ByteArray)
{
    try
    {
        // Open file for writing
        System::IO::FileStream ^_FileStream = gcnew System::IO::FileStream(_FileName, System::IO::FileMode::Create, System::IO::FileAccess::Write);

        // Writes a block of bytes to this stream using data from a byte array.
        _FileStream->Write(_ByteArray, 0, _ByteArray->Length);

        // close file stream
        _FileStream->Close();

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

    // error occured, return false
    return false;
}


Here is a simple example showing how to use above function (ByteArrayToFile). In this example we save byte array variable _ByteArray into a file byte-array.dat.

array<System::Byte> ^_ByteArray = ..... some data .....;

ByteArrayToFile("c:\\image-object.dat", _ByteArray);


C++/CLI Keywords Used:

  • FileStream
  • FileAccess
  • FileMode
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, SQL, Byte array to file, FileMode, FileAccess
  • Programming Language : C++/CLI

External Resources:

Leave a comment