C# Binary Serialization Example

← All NMath Code Examples

 

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

using CenterSpace.NMath.Core;

namespace CenterSpace.NMath.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
      var u = new DoubleVector( "[ 5.6 4.2 5.4 -0.004 434 ]" );

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

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

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

    } // Main

  }// class

}// namespace


← All NMath Code Examples
Top