Skip to content

Instantly share code, notes, and snippets.

@mstewio
Last active August 2, 2017 19:41
Show Gist options
  • Save mstewio/eb9a7a5df2f84a44fe29f1a03e8b4e20 to your computer and use it in GitHub Desktop.
Save mstewio/eb9a7a5df2f84a44fe29f1a03e8b4e20 to your computer and use it in GitHub Desktop.
BinaryFormatterImplementation
using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace ConsoleDev
{
public class BinaryFormatterImplementation
{
public static void Main(string[] args)
{
Serialize();
Deserialize();
}
static void Serialize()
{
var manager = new SaveManager();
FileStream fs = new FileStream("DataFile.dat", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, manager);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
}
static void Deserialize()
{
SaveManager manager = null;
FileStream fs = new FileStream("DataFile.dat", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
manager = (SaveManager)formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
// Writes 1.5
Console.WriteLine(manager.Version);
}
}
[Serializable]
public class SaveManager
{
[OptionalField]
public float Version = 1.5f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment