/* Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Xml.Serialization; namespace Utilities { /// <summary> /// Helps with serializing an object to XML and back again. /// </summary> public static class Serialization { /// <summary> /// Deserializes an object from binary /// </summary> /// <typeparam name="T">Type of the object</typeparam> /// <param name="Binary">Binary representation of the object</param> /// <param name="Object">Object after it is deserialized</param> public static void BinaryToObject<T>(byte[] Binary,out T Object) { try { using (MemoryStream Stream = new MemoryStream()) { Stream.Write(Binary, 0, Binary.Length); Stream.Seek(0, 0); BinaryFormatter Formatter = new BinaryFormatter(); Object = (T)Formatter.Deserialize(Stream); } } catch { throw; } } } }
Serializes an object to binary
/* Copyright (c) 2010 <a href="http://www.gutgames.com">James Craig</a> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.*/ using System; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Runtime.Serialization.Formatters.Soap; using System.Text; using System.Xml.Serialization; namespace Utilities { /// <summary> /// Helps with serializing an object to XML and back again. /// </summary> public static class Serialization { /// <summary> /// Serializes an object to binary /// </summary> /// <param name="Object">Object to serialize</param> /// <param name="Output">Binary output of the object</param> public static void ObjectToBinary(object Object, out byte[] Output) { try { using (MemoryStream Stream = new MemoryStream()) { BinaryFormatter Formatter = new BinaryFormatter(); Formatter.Serialize(Stream, Object); Stream.Seek(0, 0); Output = Stream.ToArray(); } } catch { throw; } } /// <summary> /// Deserializes an object from binary /// </summary> /// <typeparam name="T">Type of the object</typeparam> /// <param name="Binary">Binary representation of the object</param> /// <param name="Object">Object after it is deserialized</param> public static void BinaryToObject<T>(byte[] Binary,out T Object) { try { using (MemoryStream Stream = new MemoryStream()) { Stream.Write(Binary, 0, Binary.Length); Stream.Seek(0, 0); BinaryFormatter Formatter = new BinaryFormatter(); Object = (T)Formatter.Deserialize(Stream); } } catch { throw; } } } }
Collection Serialization
using System; using System.IO; using System.Collections; using System.Runtime.Serialization.Formatters.Soap; using System.Runtime.Serialization.Formatters.Binary; class MainClass { private static void BinarySerialize(ArrayList list) { using (FileStream str = File.Create("people.bin")) { BinaryFormatter bf = new BinaryFormatter(); bf.Serialize(str, list); } } private static ArrayList BinaryDeserialize() { ArrayList people = null; using (FileStream str = File.OpenRead("people.bin")) { BinaryFormatter bf = new BinaryFormatter(); people = (ArrayList)bf.Deserialize(str); } return people; } private static void SoapSerialize(ArrayList list) { using (FileStream str = File.Create("people.soap")) { SoapFormatter sf = new SoapFormatter(); sf.Serialize(str, list); } } private static ArrayList SoapDeserialize() { ArrayList people = null; using (FileStream str = File.OpenRead("people.soap")) { SoapFormatter sf = new SoapFormatter(); people = (ArrayList)sf.Deserialize(str); } return people; } public static void Main() { ArrayList people = new ArrayList(); people.Add("G"); people.Add("L"); people.Add("A"); BinarySerialize(people); SoapSerialize(people); ArrayList binaryPeople = BinaryDeserialize(); ArrayList soapPeople = SoapDeserialize(); Console.WriteLine("Binary people:"); foreach (string s in binaryPeople) { Console.WriteLine(" " + s); } Console.WriteLine(" SOAP people:"); foreach (string s in soapPeople) { Console.WriteLine(" " + s); } } }
Deserialize
using System; using System.IO; using System.Text; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; [Serializable] class Employee : ISerializable { private string name; private int age; private string address; public Employee(string name, int age, string address) { this.name = name; this.age = age; this.address = address; } private Employee(SerializationInfo info, StreamingContext context) { name = info.GetString("Name"); age = info.GetInt32("Age"); try { address = info.GetString("Address"); } catch (SerializationException) { address = null; } } public string Name { get { return name; } set { name = value; } } public int Age { get { return age; } set { age = value; } } public string Address { get { return address; } set { address = value; } } public void GetObjectData(SerializationInfo inf, StreamingContext con) { inf.AddValue("Name", name); inf.AddValue("Age", age); if ((con.State & StreamingContextStates.File) == 0) { inf.AddValue("Address", address); } } public override string ToString() { StringBuilder str = new StringBuilder(); str.AppendFormat("Name: {0} ", Name); str.AppendFormat("Age: {0} ", Age); str.AppendFormat("Address: {0} ", Address); return str.ToString(); } } public class MainClass { public static void Main(string[] args) { Employee roger = new Employee("R", 56, "L"); Console.WriteLine(roger); Stream str = File.Create("r.bin"); BinaryFormatter bf = new BinaryFormatter(); bf.Context = new StreamingContext(StreamingContextStates.CrossAppDomain); bf.Serialize(str, roger); str.Close(); str = File.OpenRead("r.bin"); bf = new BinaryFormatter(); roger = (Employee)bf.Deserialize(str); str.Close(); Console.WriteLine(roger); str = File.Create("r.bin"); bf = new BinaryFormatter(); bf.Context = new StreamingContext(StreamingContextStates.File); bf.Serialize(str, roger); str.Close(); str = File.OpenRead("r.bin"); bf = new BinaryFormatter(); roger = (Employee)bf.Deserialize(str); str.Close(); Console.WriteLine(roger); } }
illustrates binary serialization
/* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110 */ /* Example15_19.cs illustrates binary serialization */ using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; // the Customer class gives us something to serialize [Serializable] class Customer { // some private data members private int CustomerNumber; private string CustomerName; private string CustomerCountry; // the WriteCustomer method formats info to the screen public void WriteCustomer() { Console.WriteLine("Customer Number: " + this.CustomerNumber); Console.WriteLine("Customer Name: " + this.CustomerName); Console.WriteLine("Customer Country: " + this.CustomerCountry); } // the constructor accepts all the info to create a customer public Customer( int newCustomerNumber, string newCustomerName, string newCustomerCountry) { this.CustomerNumber = newCustomerNumber; this.CustomerName = newCustomerName; this.CustomerCountry = newCustomerCountry; } } public class Example15_19 { public static void Main() { // create a new customer and dump to screen Customer MyCustomer = new Customer(1, "X Corporation", "France"); MyCustomer.WriteCustomer(); // Create a FileStream to hold the serialized customer FileStream serializeStream = new FileStream("c:MyCustomer.dat", FileMode.Create); // use the CLR's binary formatting support BinaryFormatter bf = new BinaryFormatter(); // serialize the object bf.Serialize(serializeStream, MyCustomer); serializeStream.Flush(); serializeStream.Close(); // retrieve the serialized version to a second object and dump that FileStream retrieveStream = new FileStream("c:MyCustomer.dat", FileMode.Open); Customer NewCustomer = (Customer) bf.Deserialize(retrieveStream); NewCustomer.WriteCustomer(); } }
Set XML tag name for Serialization
using System; using System.IO; using System.Xml.Serialization; public class Serializer { public static void Main(string [] args) { Personnel personnel = CreatePersonnel(); XmlSerializer serializer = new XmlSerializer(typeof(Personnel)); using (FileStream stream = File.OpenWrite("Employees.xml")) { serializer.Serialize(stream, personnel); } } private static Personnel CreatePersonnel() { Personnel personnel = new Personnel(); personnel.Employees = new Employee [] {new Employee()}; personnel.Employees[0].FirstName = "Joe"; personnel.Employees[0].MiddleInitial = "M"; personnel.Employees[0].LastName = "Lee"; personnel.Employees[0].Addresses = new Address [] {new Address()}; personnel.Employees[0].Addresses[0].AddressType = AddressType.Home; personnel.Employees[0].Addresses[0].Street = new string [] {"999 Colluden"}; personnel.Employees[0].Addresses[0].City = "Vancouver"; personnel.Employees[0].Addresses[0].State = State.BC; personnel.Employees[0].Addresses[0].Zip = "V5V 4X7"; personnel.Employees[0].HireDate = new DateTime(2001,1,1); return personnel; } } [Serializable] public enum AddressType { Home, Office } [Serializable] public enum State { [XmlEnum(Name="British C")]BC, [XmlEnum(Name="Sask")]SK } [Serializable] public class Address { [XmlAttribute(AttributeName="type")] public AddressType AddressType; [XmlElement(ElementName="street")] public string[] Street; [XmlElement(ElementName="city")] public string City; [XmlElement(ElementName="state")] public State State; [XmlElement(ElementName="zip")] public string Zip; } [Serializable] public class TelephoneNumber { [XmlAttribute(AttributeName="type")] public AddressType AddressType; [XmlElement(ElementName="areacode")] public string AreaCode; [XmlElement(ElementName="exchange")] public string Exchange; [XmlElement(ElementName="number")] public string Number; } [Serializable] public class Employee { [XmlAttribute(AttributeName="firstname")] public string FirstName; [XmlAttribute(AttributeName="middleinitial")] public string MiddleInitial; [XmlAttribute(AttributeName="lastname")] public string LastName; [XmlArray(ElementName="addresses")] [XmlArrayItem(ElementName="address")] public Address [] Addresses; [XmlArray(ElementName="telephones")] [XmlArrayItem(ElementName="telephone")] public TelephoneNumber [] TelephoneNumbers; [XmlAttribute(AttributeName="hiredate")] public DateTime HireDate; } [Serializable] [XmlRoot(ElementName="personnel")] public class Personnel { [XmlElement(ElementName="employee")] public Employee [] Employees; }
Serial Employee class
using System; using System.IO; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Soap; class SoapTest { public static void Main() { SerialEmployee emp1 = new SerialEmployee(); SerialEmployee emp2 = new SerialEmployee(); emp1.EmployeeID = 1; emp1.LastName = "B"; emp1.FirstName = "K"; emp1.YearsService = 12; emp1.Salary = 35000.50; emp2.EmployeeID = 2; emp2.LastName = "B"; emp2.FirstName = "J"; emp2.YearsService = 9; emp2.Salary = 23700.30; Stream str = new FileStream("soaptest.xml", FileMode.Create, FileAccess.ReadWrite); IFormatter formatter = new SoapFormatter(); formatter.Serialize(str, emp1); formatter.Serialize(str, emp2); str.Close(); } } [Serializable] public class SerialEmployee { public int EmployeeID; public string LastName; public string FirstName; public int YearsService; public double Salary; public SerialEmployee() { EmployeeID = 0; LastName = null; FirstName = null; YearsService = 0; Salary = 0.0; } }