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.Linq;
- using System.Text;
- using System.Xml.Serialization;
- namespace ConsoleApplication1
- {
- class Program
- {
- static void Main(string[] args)
- {
- // Create a List of values that will eventually be serialized.
- List<Employee> EmployeeList1 = new List<Employee>();
- 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"));
- Serialize(EmployeeList1);
- List<Employee> EmployeeList2 = Deserialize();
- // display the results
- foreach (Employee Employee in EmployeeList2)
- {
- Console.WriteLine("{0}, {1}, {2}",
- Employee.id,
- Employee.fName,
- Employee.sName);
- }
- Console.ReadLine();
- }
- private static void Serialize(List<Employee> EmployeeList)
- {
- // Use a file stream here.
- using (TextWriter WriteFileStream = new StreamWriter("test.xml"))
- {
- // Construct a SoapFormatter and use it
- // to serialize the data to the stream.
- XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Employee>));
- try
- {
- // Serialize EmployeeList to the file stream
- SerializerObj.Serialize(WriteFileStream, EmployeeList);
- }
- catch (Exception ex)
- {
- Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
- }
- }
- }
- private static List<Employee> Deserialize()
- {
- List<Employee> EmployeeList2 = new List<Employee>();
- // Create a new file stream for reading the XML file
- using (FileStream ReadFileStream = new FileStream("test.xml", FileMode.Open, FileAccess.Read, FileShare.Read))
- {
- // Construct a XmlSerializer and use it
- // to serialize the data from the stream.
- XmlSerializer SerializerObj = new XmlSerializer(typeof(List<Employee>));
- try
- {
- // Deserialize the hashtable from the file
- EmployeeList2 = (List<Employee>)SerializerObj.Deserialize(ReadFileStream);
- }
- catch (Exception ex)
- {
- Console.WriteLine(string.Format("Failed to serialize. Reason: {0}", ex.Message));
- }
- }
- // return the Deserialized data.
- return EmployeeList2;
- }
- }
- // The object we are going to Serializing/De-serializing
- [Serializable()]
- public class Employee
- {
- public int id { get; set; }
- public string fName { get; set; }
- public string sName { get; set; }
- public Employee()
- {
- }
- public Employee(int i, string f, string s)
- {
- id = i;
- fName = f;
- sName = s;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement