51.1 Binary Serialization (.NET, C#, CSharp, VB, Visual Basic, F#)
The System.Runtime.Serialization.Formatters.Binary.BinaryFormatter class provides Serialize() and Deserialize() methods for persisting an object in binary format to a given stream. For example, this code serializes two FloatComplexMatrix objects to a file:
Code Example – C# binary serialization
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
var A =
new FloatComplexMatrix( "2x2[ (5,9.8) (-6,.9) (7,-8) (8,8) ]" );
var B = new FloatComplexMatrix( 4, 4, .1F, .1F );
FileStream binStream = File.Create( "myData.dat" );
var binFormatter = new BinaryFormatter();
binFormatter.Serialize( binStream, A );
binFormatter.Serialize( binStream, B );
binStream.Close();
Code Example – VB binary serialization
Imports System.IO
Imports System.Runtime.Serialization.Formatters.Binary
Dim A As New FloatComplexMatrix(
"2x2[ (5,9.8) (-6,.9) (7,-8) (8,8) ]")
Dim B As New FloatComplexMatrix(4, 4, 0.1F, 0.1F)
Dim BinStream As FileStream = File.Create("myData.dat")
Dim BinFormatter As New BinaryFormatter()
BinFormatter.Serialize(BinStream, A)
BinFormatter.Serialize(BinStream, B)
BinStream.Close()
This code restores the objects from the file:
Code Example – C# binary serialization
binStream = File.OpenRead( "myData.dat" );
FloatComplexMatrix A2 =
(FloatComplexMatrix)binFormatter.Deserialize( binStream );
FloatComplexMatrix B2 =
(FloatComplexMatrix)binFormatter.Deserialize( binStream );
binStream.Close();
File.Delete( "myData.dat" );
Code Example – VB binary serialization
BinStream = File.OpenRead("myData.dat")
Dim A2 = CType(BinFormatter.Deserialize(BinStream),
FloatComplexMatrix)
Dim B2 = CType(BinFormatter.Deserialize(BinStream),
FloatComplexMatrix)
BinStream.Close()
File.Delete("myData.dat")