Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Runtime.Serialization;
- using System.Text;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- while (true)
- {
- Console.WriteLine("s=serialize, r=read:");
- switch (Console.ReadLine())
- {
- case "s": // save the collection of objects
- var EmployeeList1 = new List<Employee>();
- // create some objects adding them to a List
- EmployeeList1.Add(new Employee(1, "Elenor", "Scheller"));
- EmployeeList1.Add(new Employee(2, "Kaila", "Wilburn"));
- EmployeeList1.Add(new Employee(3, "Shea", "Wallen"));
- EmployeeList1.Add(new Employee(4, "Elliot", "Shaffer"));
- EmployeeList1.Add(new Employee(5, "Dominica", "Charney"));
- try // try to serialize the collection to a file
- {
- using (Stream stream = File.Open("data.xml", FileMode.Create))
- {
- // create DataContractSerializer
- DataContractSerializer serializer = new DataContractSerializer(EmployeeList1.GetType());
- // serialize the collection (EmployeeList1) to file (stream)
- serializer.WriteObject(stream, EmployeeList1);
- }
- }
- catch (IOException)
- {
- }
- break;
- case "r": // read the collection of object
- try
- {
- using (Stream stream = File.Open("data.xml", FileMode.Open))
- {
- // create DataContractSerializer
- DataContractSerializer serializer = new DataContractSerializer(new List<Employee>().GetType());
- // deserialize the collection (Employee) from file (stream)
- var EmployeeList2 = (List<Employee>)serializer.ReadObject(stream);
- // display the results
- foreach (Employee Employee in EmployeeList2)
- {
- Console.WriteLine("{0}, {1}, {2}",
- Employee.id,
- Employee.fName,
- Employee.sName);
- }
- }
- }
- catch (IOException)
- {
- }
- break;
- }
- }
- }
- }
- // The object we are going to Serializing/De-serializing
- [DataContract]
- class Employee
- {
- [DataMember]
- public int id { get; set; }
- [DataMember]
- public string fName { get; set; }
- [DataMember]
- public string sName { get; set; }
- public Employee(int i, string f, string s)
- {
- id = i;
- fName = f;
- sName = s;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement