Simple example of serialization/deserialization

Here’s a simple console application demonstrating serialization and deserialization. The current culture is serialized to a file called myfile.bin then deserialized and cast back to a CultureInfo object.

using System;
using System.Text;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System.Globalization;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      CultureInfo ci = CultureInfo.CurrentCulture;

      using (FileStream fs = new FileStream(
       
@"C:\myfile.bin",
       
FileMode.OpenOrCreate,
       
FileAccess.ReadWrite))
      {
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(fs, ci);

        fs.Close();
      }

      CultureInfo obj = null;
      using (FileStream fs = new FileStream(
        @"C:\myfile.bin",
        FileMode.Open,
        FileAccess.Read))
      {
        BinaryFormatter bf = new BinaryFormatter();
        obj = (CultureInfo)bf.Deserialize(fs);
        fs.Close();
      }

      Console.WriteLine(obj.Name);

      Console.ReadKey();
    }
  }
}

Tags: , ,

Leave a Reply