Skip to content

Instantly share code, notes, and snippets.

@dnasca
Created March 17, 2015 06:40
Show Gist options
  • Select an option

  • Save dnasca/060bea75b488940ed953 to your computer and use it in GitHub Desktop.

Select an option

Save dnasca/060bea75b488940ed953 to your computer and use it in GitHub Desktop.
Serialization basics
using System;
using System.Diagnostics;
using System.Runtime.Serialization.Formatters;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class Program
{
public static void Main()
{
//create an array with a few items
Computer[] computers =
{
new Computer(1, "Laptop"),
new Computer(2, "Desktop"),
new Computer(3, "Tablet"),
};
//create some reference variables for FileStream and BinaryFormatter methods
var fileStream = new FileStream(@"C:\SampleFiles\Computers.dat", FileMode.Create);
var serializer = new BinaryFormatter();
//serialize the array to the path provided in the FileStream method and close
serializer.Serialize(fileStream, computers);
fileStream.Close();
//create a new reference of FileStream method, this time to open
fileStream = new FileStream(@"C:\SampleFiles\Computers.dat", FileMode.Open);
//create a new array called serializedData which accesses BinaryFormatter.Deserialize
//this will convert type object to type array, we must use a cast here
Computer[] serializedData = (Computer[])serializer.Deserialize(fileStream);
fileStream.Close();
//loop through the deserialized array and print its contents
foreach (var computer in serializedData)
{
Console.WriteLine("Description: " + computer.Description);
}
Console.ReadLine();
}
}
[Serializable]
class Computer
{
public int Id { get; set; }
public string Description { get; set; }
public Computer()
{
}
public Computer(int id, string description)
{
this.Id = id;
this.Description = description;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment