C# Binary Serialization Example

[TOC]

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.Core.Examples.CSharp
{
  /// <summary>
  /// A .NET example in C# showing how to serialize and deserialize an NMath object 
  /// in binary format.
  /// </summary>
  class BinarySerializationExample
  {
    private const string filename = "data.dat";

    static void Main( string[] args )
    {
      Console.WriteLine();

      // Delete old file, if it exists
      if ( File.Exists( filename ) )
      {
        Console.WriteLine( "Deleting old file" );
        File.Delete( filename );
      }

      // Create vector
      DoubleVector u = new DoubleVector( "[ 5.6 4.2 5.3 -0.004 434 ]" );

      // Persist to file
      FileStream stream = File.Create( filename );
      BinaryFormatter formatter = new BinaryFormatter();
      Console.WriteLine( "Serializing vector" );
      formatter.Serialize( stream, u );
      stream.Close();

      // Restore from file
      stream = File.OpenRead( filename );
      Console.WriteLine( "Deserializing vector" );
      DoubleVector v = (DoubleVector) formatter.Deserialize( stream );
      stream.Close();

      Console.WriteLine();
      Console.WriteLine( "Press Enter Key" );
      Console.Read();

    } // Main

  }// class

}// namespace


[TOC]