Last active
August 2, 2017 19:41
-
-
Save mstewio/eb9a7a5df2f84a44fe29f1a03e8b4e20 to your computer and use it in GitHub Desktop.
BinaryFormatterImplementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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