Object To File Function

public static bool ObjectToFile(object _Object, string _FileName)
// create new memory stream
System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream();

// create new BinaryFormatter
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter _BinaryFormatter
= new 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
byte[] _ByteArray = _MemoryStream.ToArray();

// Open file for writing
//System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Create, System.IO.FileAccess.Write);
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, FileMode.Create, 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

// cleanup
_MemoryStream = null;
_ByteArray = null;

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

// Error occured, return null
return false;


Leave a Reply

Your email address will not be published. Required fields are marked *