C# Code Snippet - Load object from binary file

C# Code Snippet - Load object from binary file

C# Code Snippet - Load object from binary file

(C-Sharp) C# code snippet open an external binary data file and convert it to object. This function can be use to deserialize those byte array data (Serialized) from external file to their original objects.

Bookmark:

C# Code Snippet - Load object from binary file

This .Net C# code snippet open an external binary data file and convert it to object. This function can be use to deserialize those byte array data (Serialized) from external file to their original objects like image data ..etc. This function uses System.IO and System.Runtime.Serialization.Formatters.Binary name spaces to convert binary data file to object. 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.

Note that it will be necessary to cast the returned generic Object from the deserialization method back into the original type of object you passed in to the serialization method originally.

/// <summary>
/// Function to get object from external file
/// </summary>
/// <param name="_FileName">File name to get object</param>
/// <returns>object</returns>
public object FileToObject(string _FileName)
{
    try
    {
        // Open file for reading
        System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);

        // attach filestream to binary reader
        System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);

        // get total byte length of the file
        long _TotalBytes = new System.IO.FileInfo(_FileName).Length;

        // read entire file into buffer
        byte[] _ByteArray = _BinaryReader.ReadBytes((Int32)_TotalBytes);

        // close file reader and do some cleanup
        _FileStream.Close();
        _FileStream.Dispose();
        _FileStream = null;
        _BinaryReader.Close();

        // convert byte array to memory stream
        System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ByteArray);

        // create new BinaryFormatter
        System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
                    = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();

        // set memory stream position to starting point
        _MemoryStream.Position = 0;

        // Deserializes a stream into an object graph and return as a object.
        return _BinaryFormatter.Deserialize(_MemoryStream);
    }
    catch (Exception _Exception)
    {
        // Error
        Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
    }

    // Error occured, return null
    return null;
}


Here is a simple example showing how to use above function (FileToObject). In this example we read binary data from external file (image-object.dat) and convert byte array into object, in this case it's an image object, and show the image in picturebox.

pictureBox2.Image = (Image)FileToObject("c:\\image-object.dat");


C# Keywords Used:

  • FileStream
  • BinaryReader
  • FileInfo
  • FileMode
  • FileAccess
  • MemoryStream
  • BinaryFormatter
  • Deserialize
  • byte
  • Exception

Code Snippet Information:

  • Applies To: Visual Studio, .Net, C#, CLI, Byte Array, File to object, FileStream, BinaryReader, FileMode, BinaryFormatter, Deserialize, Cache control, Load objects from file
  • Programming Language : C# (C-Sharp)

External Resources:

Kwasi Addo :: July 08-2012 :: 12:05 PM

Excellent work. Very explanatory. It becomes easy for non-programmers to follow and develop interest in programming.

Leave a comment