Created
June 26, 2015 18:15
-
-
Save csdear/c118adcc267d41d7d86a to your computer and use it in GitHub Desktop.
List : Serialize - Deserialize to Binary Format
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.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; | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment