stuart-d2
6/26/2015 - 6:15 PM

List : Serialize - Deserialize to Binary Format

List : Serialize - Deserialize to Binary Format

/*
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
*/

[Serializable()] 
public class Lizard
{
	public string Type { get; set;}
	public int Number {get; set;}  
	public bool Healthy {get; set;} 
	
	public Lizard(string t, int n, bool h)
	{
		Type = t; 
		Number = n; 
		Healthy = h;
	
	}

}

public class Program 
{

static void Main()
{
	//Loop statement... to cont. while true.  
	while(true)
	{
		//Query the user for input  
		Console.WriteLine("s=serialize, r=read:");
		//User enters choice, as a case
		switch (Console.ReadLine())
		{
		case "s":
			//new anonymous type list 'Lizard' created.
			//Populated with 5 instances of Lizard
			var lizards1 = new List<Lizard>();
			lizards1.Add(new Lizard("Thorny devil", 1, true));
			lizards1.Add(new Lizard("Casquehead lizard", 0, false));
		 	lizards1.Add(new Lizard("Green iguana", 4, true));
		    lizards1.Add(new Lizard("Blotched blue-tongue lizard", 0, false));
		    lizards1.Add(new Lizard("Gila monster", 1, false));
			
			try 
			{
				//using stmnt used for a system resouce.
				//stream created 
				using (Stream stream = File.Open("data.bin", FileMode.Create))
					{
					BinaryFormatter bin = new BinaryFormatter();
				//The bin's serialize method is called, passing in the stream and passing in the anonymous lizards1 type
				// the lizards1 list object now contains alot of lizards...
					bin.Serialize(stream, lizards1);
					}
			}
				catch (IOException)
				{
				}
				break;  
				
		case "r":
			try
			{
					using (Stream stream = File.Open("data.bin", FileMode.Open))
					{
						BinaryFormatter bin = new BinaryFormatter();
						
						var lizards2 = (List<Lizard>)bin.Deserialize(stream);
						foreach (Lizard lizard in lizards2)
						{
							Console.WriteLine("{0}, {1}, {2}",
								lizard.Type,
								lizard.Number,
								lizard.Healthy); 
						}
					}
			}
			catch (IOException)
			{
			}
			break; 
			}
}
	}
}