C++/CLI Code Snippet - Save object to file

C++/CLI Code Snippet - Save object to file

C++/CLI Code Snippet - Save object to file

C++/CLI code snippet save object to external file. This function can be use to serialize objects into byte array and save them in external file.

Bookmark:

C++/CLI Code Snippet - Save object to file

This .Net C++/CLI code snippet save object to external file. This function can be use to serialize objects into byte array and save them in external file. This function uses System.IO and System.Runtime.Serialization.Formatters.Binary name spaces to save object to file. This function useful to implement database cache control system for high traffic databases by storing cached query object data in external files and read them back to database objects. Modify the exception handling section as to your project requirements.

bool ObjectToFile(System::Object ^_Object, System::String ^_FileName)
{
    try
    {
        // create new memory stream
        System::IO::MemoryStream ^_MemoryStream = gcnew System::IO::MemoryStream();

        // create new BinaryFormatter
        System::Runtime::Serialization::Formatters::Binary::BinaryFormatter ^_BinaryFormatter = gcnew System::Runtime::Serialization::Formatters::Binary::BinaryFormatter();

        // Serializes an object, or graph of connected objects, to the given stream.
        _BinaryFormatter->Serialize(_MemoryStream, _Object);

        // convert stream to byte array
        array<System::Byte> ^_ByteArray = _MemoryStream->ToArray();

        // Open file for reading
        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();

        // cleanup
        _MemoryStream->Close();
        delete _MemoryStream;
        _MemoryStream = nullptr;
        _ByteArray = nullptr;

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

    // Error occured, return null
    return false;
}


Here is a simple example showing how to use above function (ObjectToFile). This example illustrates how to save picturebox image object to external file.

ObjectToFile(pictureBox1->Image, "c:\\image-object.dat");


C++/CLI Keywords Used:

  • FileStream
  • FileMode
  • FileAccess
  • MemoryStream
  • BinaryFormatter
  • Serialize
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C++, CLI, Byte Array, Object to file, FileStream, FileMode, BinaryFormatter, Serialize, Cache control, Save object to file
  • Programming Language : C++/CLI

External Resources:

Leave a comment